多个Ajax请求(带一个回调)

时间:2016-08-05 13:59:23

标签: javascript jquery ajax

我正在发送多个ajax请求,并希望在所有请求都成功的情况下获得回调。我找到了$.when($.ajax(), [...]).then(function(results){},[...]);,但只有当你事先知道你要做多少时才会有效。在我的情况下,它取决于用户输入。

我尝试了以下内容,但我不确定$.when适合的位置或方式:

$.when(
    $('#piecesTable tr').not(':first').each(function(){

        // ...some prep...

        $.ajax({
            // ...args here...
        });
    })
).then(function() {
    // All requests are done
});

如何将所有这些$.ajax次呼叫的结果与$.when一起使用?或者我是否以其他方式处理这个问题?

3 个答案:

答案 0 :(得分:5)

我认为你所寻找的一般结构是这样的:

var requests = [];

// Populate requests array with ajax requests.
requests.push($.ajax({
    // ...
}));

// Add as many requests as you want to the array.

$.when.apply($, requests).done(function() {
    var args = $.prototype.slice.call(arguments);

    // args should contain the results of your ajax requests.

    // Do whatever with the results.
});

答案 1 :(得分:3)

这是$.when.apply($, arrayOfPromises)野兽的现代替代品:Promise.all

Promise.all(arrayOfPromises).then(function(arrayOfResults) {
    // Use arrayOfResults
});

Promise.all需要一个 thenables 数组,并返回一个promise,当所有的thenables都已解析时,该promise会使用结果数组解析。 jQuery的承诺很好,因为它所需要的只是它们thenables

您可以在任何支持Promise的浏览器上使用此功能,或者如果您包含Promise填充/填充。

因此,在您的情况下,您构建数组:

var arrayOfPromises = [];
$('#piecesTable tr').not(':first').each(function(){

    // ...some prep...

    arrayOfPromises.push($.ajax({       // ** Push this promise into the array
        // ...args here...
    }));
});

(或者您可以使用$.mapArray#map进行构建。)

然后使用数组:

Promise.all(arrayOfPromises).then(function(arrayOfResults) {
    // Use arrayOfResults
});

答案 2 :(得分:0)

来自jQuery文档:

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).then( myFunc, myFailure );

当两个ajax请求成功时执行函数myFunc,或者myFailure如果其中一个请求有错误。

因此,您可以使用此系统发送可变数量的请求,但仍具有相同的回调函数:)

改编自@ TW80000回答:

var requests = [];
 ....
$.when.apply($, requests ).done( myFunc, myFailure );
相关问题