jQuery ajax call returning double results
I have an ajax call in jQuery loading some elements into a div.
The call works, but for some reason is returning a duplicated response. The call should return two elements, but I get 4 (the 2 correct items, duplicated once).
Here is my ajax call:
$.ajax({
url: "<?php echo site_url('feed/editor/2'); ?>",
cache: false,
beforeSend: function(){
$('#feed-nav').after('<div class="loading"></div>', function(){
$("#feeditems").fadeOut();
});
},
success: function(html){
$('#feed .loading').fadeOut('fast', function(){
$("#feeditems").append(html).slideDown('slow');
});
}
});
return false;
I can see no reason why this might be happening!?
UPDATE
I modified the success function to the c开发者_如何学运维ode below which appears to have fixed it, although I don't really understand why.
success: function(html){
$('#feed .loading').fadeOut();
$("#feeditems").append(html).slideDown()
}
I think the issue is the the selector you are using in the success
callback, $('#feed .loading')
is matching two elements and thus calls $("#feeditems").append(html).slideDown('slow');
twice. If your markup contains an element with the loading
class on page load, the beforeSend
callback is also adding a div
with a loading
class. So you will either need to come up with a different selector in the success
callback or not have multiple div's with the loading
class.
Here I reproduce the issue:
http://jsfiddle.net/2PR4V/2/
You can add this line of code to your success
callback to see how many elements match:
console.log($('#feed .loading').size());
I fix the issue here by using a more specific selector:
http://jsfiddle.net/2PR4V/3/
精彩评论