【问题标题】:jQuery deferred AJAX calls: possible scope issuejQuery 延迟 AJAX 调用:可能的范围问题
【发布时间】:2012-02-29 13:13:08
【问题描述】:

我在一个循环中发出多个 AJAX 请求。这是我的代码:

// set defaults
var app_id = 'xxx';
var secret = 'yyy';
var auth_token = 'zzz';

// list of items to call in the API
var insights_to_check = ['application_permission_views_top_unique', 'application_installation_adds_unique', 'application_installation_removes_unique'];
var json_responses = {};

var ajax_calls = [];

// construct the API url
for (var i in insights_to_check) {
    var insight = insights_to_check[i];
    var url = 'https://graph.facebook.com/' + app_id + '/insights/' + insight + '?' + auth_token;
    ajax_calls.push(get_json(url, insight));
}

// when all ajax requests are done, call the process function
$.when.apply($, ajax_calls).done(function(){
    process_json(json_responses);
});

// collect responses to the ajax request in a global object
function get_json(url, insight) {
    $.getJSON(url, function(json) {
        json_responses[insight] = json;
    });
}

// show the global object
function process_json(all_json) {
    console.log(all_json);
}

代码有一个奇怪的问题:第一次运行时,我可以看到 AJAX 请求触发并返回,但是当 process_json() 被调用时,它会记录 undefined。如果我第二次手动调用它,它会按预期返回 json。

似乎我的延迟回调在 AJAX 请求完成之前触发,或者至少是这样。在他们能够将他们的响应分配给全局 json_responses 对象之前。任何人都可以在这里看到任何明显的东西吗?

【问题讨论】:

    标签: jquery ajax jquery-deferred


    【解决方案1】:

    我不确定为什么它会记录undefined(it does not for me,如果我省略了 Ajax 调用)但您的代码的一个问题是 .done() 回调被执行为@ 987654324@ 是一个空数组。

    你必须从get_json返回$.getJSON的返回值:

    function get_json(url, insight) {
        return $.getJSON(url, function(json) {
            json_responses[insight] = json;
        });
    }
    

    这可能会解决问题。

    【讨论】:

    • 这确实有效,我没有想到没有返回值它不会向数组添加任何内容。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-08-27
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多