如何用ajax调用返回的数据填充数组?
我正在调用一个应用程序获取数据(路由),然后通过该数据循环获取关于每个路由的附加数据。最终数据将毫无问题地显示在console.log中,但我无法将其放入数组中如何用ajax调用返回的数据填充数组?,ajax,jquery,Ajax,Jquery,我正在调用一个应用程序获取数据(路由),然后通过该数据循环获取关于每个路由的附加数据。最终数据将毫无问题地显示在console.log中,但我无法将其放入数组中 $.getJSON('http://example-app/api/routes/?callback=?', function(data) { var routes = []; $(data).each(function(i){ routes.push(d
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var routes = [];
$(data).each(function(i){
routes.push(data[i]._id);
});
function getRouteData(route, callback) {
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json',
success: function(data) {
callback(data);
}
});
}
var route_data = [];
$(routes).each(function(i) {
getRouteData(routes[i], function(data) {
console.log(data); // this shows me the 13 objects
route_data.push(data);
});
});
console.log(route_data); // this is empty
});
nnnnnn是的,您必须使用延迟/承诺来确保
route\u数据在发送到控制台之前已填充
如何做到这一点目前还不清楚,特别是考虑到$.when()
接受一系列离散参数,而不是数组这一事实
另一个问题是,任何单个ajax失败都不应该破坏整个企业。如何克服这一点可能不太明显
我不是百分之百确定,但以下几点应该是可行的:
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var route_promises = [];
var route_data = [];
function getRouteData(route) {
var dfrd = $.Deferred();
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json'
}).done(function(data) {
//console.log(data); // this shows me the 13 objects
route_data.push(data);
}).fail(function() {
route_data.push("ajax error");
}).then(function() {
dfrd.resolve();
});
return dfrd.promise();//By returning a promise derived from a Deferred that is fully under our control (as opposed to the $.ajax method's jqXHR object), we can guarantee resolution even if the ajax fails. Thus any number of ajax failures will not cause the whole route_promises collection to fail.
}
$(data).each(function(i, route) {
route_promises.push( getRouteData(route) );
});
//$.when doesn't accept an array, but we should be able to use $.when.apply($, ...), where the first parameter, `$`, is arbitrary.
$.when.apply($, route_promises).done(function() {
console.log(route_data);
});
});
未经测试
查看代码中的注释。我怀疑回调=?
正在将其转换为一个jsonp请求,该请求将始终是异步的(即使您指定了async:false
)……对,我想async:false没有任何意义-它确实是jsonp,并且必须是异步的,因为请求是到外部站点的。编辑以删除该行。因此,在获得“this is empty”注释的行中,异步回调尚未发生,因此数组实际上是空的。在收到所有回复后,您应该能够利用功能做一些事情。看看关于循环中异步Ajax的另一个问题。。。