问题
I'm working on a bookmarking function (codeigniter, jquery, ajax). Below is the HTML for the form and the jQuery code.
Here's what's happening:
- form is submitting the data to the database
- the page is reloading
- I'm not getting the success alert
- If I use e.preventDefault() or return false, the page doesn't reload and I get the success alert, but the data that gets passed to the database is 0.
HTML FORM
<?php echo form_open('bookmarks/addBookmark'); ?>
<?php echo form_hidden('bookn', $bname); ?>
<?php echo form_hidden('booki', $this->uri->segment(4, 0)); ?>
<button class="bb_button">Bookmark</button>
<?php echo form_close(); ?>
jQuery
$('.bb_button').click(function() {
$.ajax({
url: 'bookmarks/addBookmark',
type: 'POST',
success: function (result) {
alert("Your bookmark has been added.");
}
});
//return false<--this is where I used it
});
回答1:
You're not passing any data in.
Try
$('.bb_button').click(function(e) {
$.ajax({
url: 'bookmarks/addBookmark',
type: 'POST',
data: { bookn: $("[name='bookn']").val(), booki: $("[name='booki']").val() },
success: function (result) {
alert("Your bookmark has been added.");
}
});
e.preventDefault();
});
来源:https://stackoverflow.com/questions/10432556/stop-page-load-in-codeigniter-jquery-ajax-bookmark-function