我需要进行多次ajax调用(确切的数量是可变的)并等待它们全部完成。我当前的代码如下:
ajaxRequests = new Array();
ajaxRequests.push(function(){
return jQuery.post(url: "someUrl",
dataType: "json",
data: yourJsonData
});
jQuery.when.apply(jQuery, ajaxRequests).done(function(){
alert("ajax requests done");
});
不幸的是,上面的代码没有等待ajax请求完成。任何帮助将不胜感激。
最佳答案
答案如下:复制自jQuery .when troubleshooting with variable number of arguments
// Array of requests
var requests = Array();
requests.push($.get('responsePage.php?data=foo'));
requests.push($.get('responsePage.php?data=bar'));
var defer = $.when.apply($, requests);
defer.done(function(){
// This is executed only after every ajax request has been completed
$.each(arguments, function(index, responseData){
// "responseData" will contain an array of response information for each specific request
});
});
关于jQuery 进行动态 ajax 调用并等待它们完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17329294/