我是Javascript的新手。我的脚本发生了一些问题 我不得不循环遍历$ .get,我在这里停留了一个循环是我的代码
a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"]
for (var i = 0; i < a.length; i+=1){
.$get('url' + "?params=" + a[i],function(data2){
school = data2['data'];
});
}
console.log(school);
当我尝试console.log(学校)时,它会一直显示&#34; object {}&#34;
如何在循环外获取数据?
如果你能帮我解决这个问题,我将非常感激。
感谢。
答案 0 :(得分:1)
你必须使用回调函数或类似的东西。
因为$ .get是异步函数,而
时console.log(school);
执行(!)学校尚未评估。
你可以使用这样的东西。
a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"]
for (var i = 0; i < a.length; i+=1){
.$get('url' + "?params=" + a[i],function(data2){
school = data2['data'];
console.log(school);
});
}
或
a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"]
var school ={};
for (var i = 0; i < a.length; i+=1){
.$get('url' + "?params=" + a[i],function(data2){
school = data2['data'];
whenitready();
});
}
function whenitready(){
console.log(school);
}
答案 1 :(得分:0)
如果你需要等到所有请求都完成,你需要这样的事情:
var endpoints = [];
for (var i = 0; i < a.length; i+=1) {
endpoints.push($.get('url' + '?params=' + a[i]));
}
$.when.apply($, endpoints).done(function () {
// Function arguments array differs if we have one or more than one endpoint.
// When called with one endpoint arguments is an array of three elements [data, textStatus, jqXHR].
// When called with more than one endpoint arguments is an array of arrays [[data, textStatus, jqXHR], ...].
// Normalize the single endpoint to the generic list one.
var args = endpoints.length > 1 ? arguments : [arguments];
for (var i = 0; i < args.length; i++) {
var data = args[i][0];
// Do stuff here with every data received...
school = ...
}
console.log(school);
});