Ajax Post method using jquery
<script type='text/javascript'>
$("#cart").click(function() {
var loadUrl = "ajax_redirect.php";
var val = "2";
$.post(loadUrl,
{ page: "cart", data: val },
function(data)
{
alert(data);
alert("Course added to Cart");
}
);
});
</script>
<body>
`<a class="button" id="cart" href="#" title="Apply"><img src="images/button.png" alt="apply" />Apply</a>`
</body>
I开发者_运维技巧f i click the <a>
link nothing happens but refreshing. I am not able to get return data value.
Your script is run before the a
element exists and is ready in the DOM. You should have wrapped the entire thing in a $(document).ready()
call, like so:
$(document).ready (function () {
$("#cart").click(function(event) {
event.preventDefault ();
var loadUrl = "ajax_redirect.php";
var val = "2";
$.post(loadUrl,
{ page: "cart", data: val },
function(data)
{
alert(data);
alert("Course added to Cart");
}
);
});
});
Also note the event.preventDefault()
, to prevent the link from doing it's default action
精彩评论