jQuery进行动态ajax调用并等待它们完成

时间:2013-06-26 19:56:32

标签: jquery

我需要进行一些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请求完成。任何帮助都会得到赞赏。

1 个答案:

答案 0 :(得分:4)

答案如下:从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
    });

});