Ajax request in progress jQuery

2020-02-10 18:24发布

Is there a way to check if there's ajax request in progress? Something like:

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

5条回答
Melony?
2楼-- · 2020-02-10 18:59

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.

查看更多
趁早两清
3楼-- · 2020-02-10 19:01

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.

查看更多
放荡不羁爱自由
4楼-- · 2020-02-10 19:08

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);
        });
    });
});
查看更多
Rolldiameter
5楼-- · 2020-02-10 19:20

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;

} 
查看更多
家丑人穷心不美
6楼-- · 2020-02-10 19:25

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

查看更多
登录 后发表回答