jQuery - 在AJAX延期完成后运行唯一回调

时间:2014-01-23 23:12:08

标签: jquery ajax deferred

我很困惑我应该如何推迟多个AJAX请求,然后在完成所有请求后使用各自的传入AJAX数据运行每个请求的回调函数。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果你真的想在所有ajax调用完成之前不运行任何东西,那么你需要安装一个完成函数,它只是将完成参数存储到一个对象数组中,当完成所有操作后,你可以直接遍历数组,处理每组结果。

// set numRequests to the total number of ajax requests you're doing
var numRequests = x;

// initialize results array
var results = [];

// use storeResults as your success handler for each ajax call
function storeResults(data, status, jqXHR) {
    results.push({data: data, status: status, jqXHR: jqXHR});
    if (results.length === numRequests) {
        // all results are in the array now, so process them all
    }
}

或者,如果你为每个ajax调用都有一个单独的完成处理程序并希望跟踪它们,但仍然不想处理它们中的任何一个,直到所有结果都存在,你可以这样做:

var results = [];
var numRequests = 0;
function addCompletionHandler(fn) {
    ++numRequests;
    return function(data, status, jqXHR) {
        // store the response data
        results.push({data: data, status: status, jqXHR: jqXHR, fn: fn});

        // if all requests are done, then process them all by calling all their
        // success handlers one after another
        if (results.length === numRequests) {
            for (var i = 0; i < results.length; i++) {
                var item = results[i];
                item.fn(item.data, item.status, item.jqXHR);
            }
        }
    };
}

// make multiple ajax calls
// all completion handlers will be called only when all the ajax calls have finished
$.ajax({type: 'POST', 
        url: 'whatever1.php', 
        data: whatever1, 
        success: addCompletionHandler(function(data, status, jqXHR) {
            // completion handler for this ajax call
        })
});
$.ajax({type: 'POST', 
        url: 'whatever2.php', 
        data: whatever2, 
        success: addCompletionHandler(function(data, status, jqXHR) {
            // completion handler for this ajax call
        })
});
$.ajax({type: 'POST', 
        url: 'whatever32.php', 
        data: whatever3, 
        success: addCompletionHandler(function(data, status, jqXHR) {
            // completion handler for this ajax call
        })
});