ajax循环请求,不能使用for循环,原因如下:
1. 因为ajax是异步执行,在还没有拿到服务器响应内容,就进入下一个for循环中
解决办法:递归
currentIndex = 0; function ajax(){ if(currentIndex>=20){ return; } var url = 'url'; console.log(i); $.ajax({ type: 'get', url: url, dataType: "json", async: true, cache: true, success: function(json){ currentIndex++; console.log("test"); ajax(); }, error: function(data){ console.log("error..."); currentIndex++; ajax(); } }); }
注意:
不建议使用ajax使用同步请求,容易造成浏览器假死
参考:
http://www.cnblogs.com/eggTwo/p/5952955.html
http://blog.csdn.net/yuan882696yan/article/details/50296821
http://www.oschina.net/code/snippet_574558_13233