您的位置:首页 > Web前端 > JQuery

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

2014-07-04 11:35 567 查看
由于JS的for循环与ajax非同步运行,因此导致for循环结束了而ajax却还未执行,解决此方法有两种

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

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

asyncBooleanDefault: 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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐