3

我需要进行一些 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 请求完成。任何帮助将不胜感激。

4

1 回答 1

4

答案如下:从jQuery 复制。当使用可变数量的参数进行故障排除时

// 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
    });

});
于 2013-06-26T21:18:27.783 回答