开发者

prevent ajax call from firing repeatedly

$('.myDiv').click(function(event){
$.ajax({
        url: '',
        dataType: 'json',
        success: function(json) {

            for (var i = 0; i < json.length; i++) {
        var response = json[i];
         $('.result_new')开发者_开发知识库.append('<p>' + response.name + '</p>');
    }
        //$('.content').append('<p>' + response.total + '</p>');

        }
    });

})

event.stopPropagation()

isn't preventing the ajax call from being called repeatedly. Is there a function for this in Jquery?


$('.myDiv').click(function(){
  if( !$(this).hasClass('loading') ) {
    //add control class
    $(this).addClass('loading');
    //do ajax...
    $.ajax({
      success: function() {
        $('.myDiv').removeClass('loading')
      }
    })
 }

});


event.stopPropagation() only prevents the event from bubbling up (from .myDiv to it's parent element until reaching the window). It doesn't prevent the function from executing.

You can use various methods to identify whether the request was sent or not, for example set .data(), e.g:

$(".myDiv").click(function() {
    if (typeof $(this).data('inTheMiddleOfAnAJAXCall') == "undefined") {
        $(this).data('inTheMiddleOfAnAJAXCall', true);
        // Create an AJAX Call
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜