开发者

Ajax request in progress jQuery

Is there a way to check if ther开发者_高级运维e's ajax request in progress? Something like:

if ( $.ajax.inProgress ){ do this; } else { do that; }


yes there is


$.ajax({
     type: 'get',
     url: 'url',
     data: {
              email: $email.val()
     },
     dataType: 'text',
     success: function(data)
     {
        if(data == '1')
        {
            $response.attr('style', '')
                     .attr('style', "color:red;")
                     .html('Email already registered please enter a different email.');
        }
        else
        {
            $response.attr('style', '')
                     .attr('style', "color:green;")
                     .html('Available');
        }
     },
     beforeSend: function(){
                $email.addClass('show_loading_in_right')
     },
     complete: function(){
                $email.removeClass('show_loading_in_right')
     }
});


the beforeSend will do the process you need to do when the ajax request has just started and complete will be called when the ajax request is complete.
documentation


To abort ajax request, Use

if($.active > 0){ 
ajx.abort();//where ajx is ajax variable
}

To continue running ajax request, Use

if($.active > 0){ 
return;

} 


You should basically set a variable on top of script set to false and on ajax initiate set it to true and in the success handler set it to false again as described here.


You might like this:

$(document).ready(function() {
    var working = false;
    $("#contentLoading").ajaxSend(function(r, s) {
        $(this).show();
        $("#ready").hide();
        working = true;
    });

    $("#contentLoading").ajaxStop(function(r, s) {
        $(this).hide();
        $("#ready").show();
        working = false;
    });

    $('#form').submit(function() {
        if (working) return;
        $.post('/some/url', $(this).serialize(), function(data){
            alert(data);
        });
    });
});


If you are in full control of the javascript code you could increment a variable whenever you start an ajax request and decrement it when the request completes (with success, failure or timeout). This way you always know if there is a request in progress.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜