因爲JS的for循環與ajax非同步運行,所以致使for循環結束了而ajax卻還未執行,解決此方法有兩種php
一、設置ajax參數async爲false,即與js同步,默認是true(異步).html
這裏首先引用$.Ajax()中 async 和success的官方的解釋:jquery
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. |
代碼示例:ajax
for(int i=0;i<x;i++){異步
var html = $.ajax({
url: "some.php",
async: false
}).responseText;async
}this
2.採用遞歸循環的方法解決此問題url
function func(times){
if(times <= 0){
return;
} spa
$.get(url,data,function(){
times --;
func(times); //遞歸調用
});
}htm
func(5);