多个Ajax请求(带有一个回调) [英] Multiple Ajax Requests (with one callback)

查看:52
本文介绍了多个Ajax请求(带有一个回调)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在发送多个ajax请求,并且如果所有请求都成功,则希望获得回调.我已经找到了$.when($.ajax(), [...]).then(function(results){},[...]);,但是只有在您事先知道要执行多少操作时,它才有效.就我而言,它取决于用户输入.

I'm sending multiple ajax requests and want to get a callback if all the requests are successful. I've found $.when($.ajax(), [...]).then(function(results){},[...]); but that only works when you know in advance how many you're going to do. In my case, it varies depending on user input.

我尝试了以下操作,但不确定$.when的位置或位置:

I tried the following but I'm not sure where or how $.when fits in:

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

        // ...some prep...

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

如何将所有单独的$.ajax调用的结果与$.when一起使用?还是我可以通过其他方式处理?

How do I use the results of all those separate $.ajax calls with $.when? Or do I handle this some other way?

推荐答案

我认为您要查找的内容的一般结构如下:

I think the general structure of what you're looking for is something like this:

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

这篇关于多个Ajax请求(带有一个回调)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆