【发布时间】: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