简体   繁体   中英

In JQUERY how to find that all ajax calls in a page have been completed?

In JQUERY how to find that all ajax calls in a page have been completed?

I want to execute a method after all the ajax call are completed.

如果你正在运行许多请求而你想知道他们什么时候完成,那么你正在寻找$.ajaxStop() ,这是一个全局事件,并且“在所有AJAX请求完成后调用”, 根据到文档

If you know how many ajax call you have sent by increment some variable on each call . You can use another variable in success of ajax call to count how many times success is called . When both variables have same value you can assume all ajax calls are completed.

check on this article http://lostechies.com/joshuaflanagan/2011/10/20/coordinating-multiple-ajax-requests-with-jquery-when/

This is the code from their example:

$.when( getTweets('austintexasgov'),
        getTweets('greenling_com'),
        getTweets('themomandpops')
      ).done(function(atxArgs, greenlingArgs, momandpopsArgs){
    var allTweets = [].concat(atxArgs[0]).concat(greenlingArgs[0]).concat(momandpopsArgs[0]);
    var sortedTweets = sortTweets(allTweets);
    showTweets(sortedTweets);
      });

var getTweets = function(user){
    var url='http://twitter.com/status/user_timeline/' + user + '.json';
    return $.get(url, {count:5}, null, 'jsonp');
}

Worked perfect for me

To monitor tasks like this, you can always build a state machine. On each ajax call, add a beforeSend() callback and a complete() callback to update state to some state machine. The completed method on your state machine will conditionally execute your code if the count is at 0.

Note.... this will ONLY work if there are ajax calls with overlapping execution (running in parallel). If you have ajax calls running in serial, your state machine will execute each time all active ajax calls are in a completed state.

To work correctly with serial ajax calls, you would have to know in advance how many ajax calls you're going to make, and test against that number.

$.ajax({
    url: "test.html",
}).beforeSend(function() {
    ajaxState.started();
}).complete(function() {
    ajaxState.completed();
});

var ajaxState = {
    active: 0,
    started: function() {
        ajaxState.active++;
    },
    completed: function() {
        ajaxState.active--;
        if (!ajaxState.active) ajaxState.onComplete();
    },
    onComplete: function() {
        // Your code here.
    }
};

Maybe you call a method in the last Ajax method? There is no way to know if you've got any Ajax call made by a button for example that will be generated dynamically or whatever.

If you are sure about your last Ajax call, call a method on success.

$.ajax({
    url: "test.html",
    type: "POST",
    data: {id : menuId},
}).done(function() {
    callMethod();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM