今天需要用js 循环发送ajax请求,获取信息,
一开始,就直接按照逻辑写,
for(var i=0; i<items.length; i++){
api_url = items[i].url;
console.log(i);
$.ajax({
type: 'get',
url: api_url,
dataType: "json",
async: false,
success: function(json){
console.log("test");
var img = json.img;
},
error: function(data){
}
});
}
按照正常思维,程序应顺序执行,输出应该如下:
1
test
2
test
...
...
实际结果却非如此,输出如下:
1
2
3
...
test
test
test
而且得到的img还都是一样的,
这个结果,显然不是我要的,怎么办,想了很久,查资料,
参考: http://www.oschina.net/code/snippet_574558_13233
终于搞定,运用递归,代码如下:
currentIndex = 0;
function getImg(){
if(currentIndex>=items.length){
return;
}
var url = item[url];
console.log(i);
$.ajax({
type: 'get',
url: url,
dataType: "json",
async: false,
cache: true,
success: function(json){
currentIndex++;
console.log("test");
var img = json.img;
getImg();
},
error: function(data){
console.log("error...");
currentIndex++;
getImg();
}
});
}
通过以上写法,结果如下:
1
test
2
test
...
...
js的异步,有时候坑死人啊!