解决easyui jQuery JS的for循环调用ajax异步问题

由于JS的for循环与ajax非同步运行,因此导致for循环结束了而ajax却还未执行,解决此方法有两种

1、设置ajax参数async为false,即与js同步,默认是true(异步).

这里首先引用$.Ajax()中 async 和success的官方的解释:

async Boolean Default: true
By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

代码示例:

for(int i=0;i<x;i++){

var html = $.ajax({
url: "some.php",
async: false
}).responseText;

}

 

2.采用递归循环的方法解决此问题

function func(times){
if(times <= 0){
return;
}

$.get(url,data,function(){

times --;
func(times); //递归调用
});
}

func(5);

posted @ 2014-07-04 11:35  狂歌  阅读(12646)  评论(0编辑  收藏  举报