I have a question about using jQuery's.post()
method witho开发者_JAVA百科ut posting back the containing page.
This is code for a book page in a library system. If the user clicks on the "Return book" button, I use jQuery's .post()
to set the book returned in the database.
<form id="checkoutform">
<input type="submit" id="checkout" class="button" value="Return book" />
</form>
$(document).ready(function(){
$("#checkout").click(function() {
$.post('/transaction/', { book_id: '{{ book.id }}', user_id: username }, function(data) {
alert(data);
});
});
});
The database transaction works find, but it also posts back the page.
This is not a problem in itself, but it alters the behaviour of the Back button - and that is a problem. If the user clicks "Return book" and then uses the Back button on the browser, they will see the book page as it was before they returned the book, so it will look as though the book is still checked out.
is there a way either to:
- avoid posting back the page with the jquery
.post()
method, and just alter the parts of the page that I need, or - fix up the Back button so it goes straight back to the preceding page?
Thanks!
Actually, what's probably happening is that your click function is firing, and then, in addition, the default functionality (submit the form when a "submit" button is pressed) is occurring.
To prevent that, either make the button a plain button instead of a submit button, or add return false
at the end of your click function. Or take a look at jQuery's event.stopPropagation().
Adding return false
to the end of a jQuery event handler will prevent the default event handler from executing. Since in your case, the default behavior of submitting a form is to do a POST, that is what happens.
add return false in the end of function
$(document).ready(function(){
$("#checkout").click(function() {
$.post('/transaction/', { book_id: '{{ book.id }}', user_id: username }, function(data) {
alert(data);
});
return false;
});
});
Try throwing return false;
in the click function. Maybe it's actually submitting the page and instead of going asynchronously. If that doesn't work, what does your ajax page look like?
精彩评论