循环发送ajax请求的解决方法

今天需要用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

http://zhidao.baidu.com/link?url=XpEn58sMKMWzVF7FIAilpvEfA-AOSahtNFF1_VJrXtEvs3bNE0I_frvxiviczkVBHXkX5WQ18eVTfdJlgeAEh_


终于搞定,运用递归,代码如下:

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的异步,有时候坑死人啊!



  • 9
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值