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

H.C*_*H.C 4 javascript ajax jquery

我正在发送多个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
});
Run Code Online (Sandbox Code Playgroud)

如何使用所有这些单独$.ajax调用的结果$.when?或者我是否以其他方式处理这个问题?

TW8*_*000 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.
});
Run Code Online (Sandbox Code Playgroud)