javascript - 从 $.when .done 之外的 ajax 添加对象

标签 javascript jquery ajax

function ajaxCall1(){
    return $.ajax({
        url : 'URL1',
        data : { id : id },
        type : 'GET',
    });
}
function ajaxCall2(item_id)
{
    return $.ajax({
        url: 'URL2',
        data: { item_id: item_id },
        dataType: "text",
        type: 'GET',
    });
}

$.when(ajaxCall1()).done(function(columns){
    $.each(columns, function(column, rows) {
        $.each(rows, function(i, row) {
            $.each(row.items, function(i, item) {
                $.when(ajaxCall2(item.id)).done(function(count){
                    item.counter = count;
                });
                console.log(item);
            });
        });
    });
});

我需要从对 item 的调用中获取一个新对象 {counter:count},它是对象 row 的嵌套部分。我不知道如何实际将对象从 $.when...});

推送到项目中

最佳答案

这是关于你需要的:

ajaxCall1().done(function(columns){ // do first ajax

    var promiseArray =[]; // array for promises of subsequent ajax calls
    $.each(columns, function(column, rows) {
        $.each(rows, function(i, row) {
            $.each(row.items, function(i, item) {
                 // each call returns a promise...and also has it's own "done" to update count               
                 var promise =  ajaxCall2(item.id).done(function(count){
                    item.counter = count;
                });
                // push each promise returned from `$.ajax` into array              
                promiseArray .push(promise);                
            });
        });
    });
    // all calls will be completed, can do something with main columns array
    $.when.apply($, promiseArray).done(function(){
        /// do something with columns
    });
});

关于javascript - 从 $.when .done 之外的 ajax 添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30057338/

相关文章:

javascript - 如何统计总评论数?

javascript - 通过 ajax 返回 NULL 发布到 PHP 的音频 blob

javascript - 在新创建的链接上创建 jQuery 工具提示

javascript - 两棵花式树,其中一个选择控制另一个的内容

javascript - jQuery 手机 : Applying style after reloading content

javascript - ExtJS 4.1.1 : Custom display text for multi-select combobox

javascript - 用于设计查询语言的正则表达式

JQuery.Post() 在 Controller 中调用操作结果,MVC 3

javascript - AJAX - 如何在弹出菜单中运行脚本

javascript - 非常大数据集的 D3 TreeMap