多个AJAX调用,1个回调

时间:2014-09-22 14:02:26

标签: jquery ajax deferred

我需要使用他们的API从远程服务中获取数据(Q& A)。数据分为不同的类别,它们提供的唯一方法允许我列出特定类别的类别和项目。但是,我的简报意味着我收集了不同类别的数据。我最终这样做了(这将收集所有类别的数据):

var getEveryQA = function(sLang)
{
    var allQA = [];
    //This request is for getting category listing
    $.ajax({
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            url: category_list_URL,
            data: { Lang: sLang }, 
            dataType: "jsonp",
            success: function(responseData){
                for (var i = 0; i < responseData.length; i++) 
                {
                    if(responseData[i].Code.toLowerCase !== "all")//category "all" has no real existence although it is returned in categories listing
                    {
                        //Request items for each category
                        $.ajax({
                            crossDomain: true,
                            contentType: "application/json; charset=utf-8",
                            url: items_by_category_URL,
                            data: { Lang: sLang, Category: responseData[i].Code }, 
                            dataType: "jsonp",
                            success: function(responseData){
                                    allQA = allQA.concat(responseData);//object from this response will be concatenated to the global object
                                }
                        });

                    }
                }
            }
        }); 
}

我希望在我的for循环中完成的所有AJAX调用都成功时触发排序方法。我觉得jQuery的deferred是解决方案,但我读过的很多例子与我的for...循环结构不兼容。有没有办法建立某种&#34;队列&#34;在我的多个回调中,我可以将其作为参数传递给deferred方法?或者我看错了方向?

2 个答案:

答案 0 :(得分:3)

修改

  

这本来是一个很好(和更简单)的方法,但我不认为   它会工作。 allQA将包含所有类别的所有QA,以及   因此排序将在第一次迭代后发生(当我们所有的时候   已经推进到那个数组是第一个结果)而我需要它   当allQA“满”时出现-Bartdude

$.ajax()循环中注意for调用响应变量:_responseData(请参阅前导_下划线) - 与初始$.ajax()响应不同的变量{{1 (没有前导下划线)。

排序或其他任务应该只发生一次responseData - allQA.length === responseData.length(个人_responseData.length  响应在for循环中连接起来。)

添加,包括完成原始问题中描述的任务所不需要的其他$.ajax()deferred件 - 除非答案明确要求使用promisedeferred方法解决。

所涉及的对象或数组的

promise属性应足以完成OP中描述的任务。

jsfiddle http://jsfiddle.net/guest271314/sccf49vr/的示例文章,使用与最初发布的模式相同的模式:

length

尝试

var arr = [7, 5, 6, 1, 8, 4, 9, 0, 2, 3]; // unsorted array
$("body").append(arr + "<br />");
var getEveryQA = function (sLang) {
    var allQA = [];
    //This request is for getting category listing
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/echo/json/",
        data: {
            json: JSON.stringify(sLang)
        },
        dataType: "json",
        success: function (responseData) {
            for (var i = 0; i < responseData.length; i++) {
                // category "all" has no real existence although 
                // it is returned in categories listing
                if (responseData[i] !== "all") {
                    //Request items for each category
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/echo/json/",
                        data: {
                            json: JSON.stringify(responseData[i])
                        },
                        dataType: "json",
                        // note leading `_` underscore at `for` loop
                        // `_responseData` -- different than initial 
                        // `responseData` response from first request
                        success: function (_responseData) {
                            //object from this response will be concatenated to the global object
                            allQA = allQA.concat(_responseData);
                            // do stuff when `allQA` length === `responseData` (for loop) length
                            console.log(allQA.length === responseData.length);
                            if (allQA.length === responseData.length) {
                                // do sorting stuff
                               allQA.sort(); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                               console.log(allQA, arr);
                               $("body").append(allQA.join(",")); 
                            }
                        }
                    });
                }
            }
        }
    });
};

getEveryQA(arr);

答案 1 :(得分:2)

发表评论:使用$.when.将ajax调用放入数组中,然后调用$.when.apply(thatarray).then(function(){Do something with all the results});

您已将所有结果添加到另一个数组中(因为它们以任何顺序返回)并在then函数中对它们进行排序等:

var getEveryQA = function(sLang)
{
    var allQA = [];
    //This request is for getting category listing
    $.ajax({
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            url: category_list_URL,
            data: { Lang: sLang }, 
            dataType: "jsonp",
            success: function(responseData){
                var requests = [];
                for (var i = 0; i < responseData.length; i++) 
                {
                    if(responseData[i].Code.toLowerCase !== "all")//category "all" has no real existence although it is returned in categories listing
                    {
                        //Request items for each category
                        requests.push($.ajax({
                            crossDomain: true,
                            contentType: "application/json; charset=utf-8",
                            url: items_by_category_URL,
                            data: { Lang: sLang, Category: responseData[i].Code }, 
                            dataType: "jsonp",
                            success: function(responseData){
                                    allQA = allQA.concat(responseData);//object from this response will be concatenated to the global object
                                }
                        }));
                    }
                }
                $.when.apply(requests).then(function(){
                    // Do something with your responses in allQA
                });
            }
        }); 
}

来自$.ajax的返回值是可以与其他承诺汇总的承诺。 $.when是唯一可以接受一系列承诺的方法,让您在所有完成后(或任何失败)执行操作。