由於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);
