我運行名爲像checker
每60秒這樣的函數調用:多AJAX而不阻斷
setInterval(checker, 60 * 1000);
checker
具有它通過AJAX檢查URL的陣列,當前碼是這樣的:
$.ajax({
url: sites[i].url,
type: "GET",
dataType: "json",
async: false,
success: function(data){
//blah blah blah
}else{
//something else
},
error: function(){
//blah blah blah
}
});
代碼工作,根據JSON的結果改變一些基於UI的東西。我的問題是,檢查多個站點的執行時間約爲4秒,此時該頁面此時無響應。如果我刪除async: false
代碼不再按預期工作。
有人提到使用回調來解決問題,但不明白如何在這種情況下使用它們。
編輯
從adosan根據建議更新代碼:
function promtest(){
var sites = [
{ name: "WorkingSite", url: "http://sitename.com/testing.php" },
//a bunch more sites, 1 returns a 404 to test for failure
{ name: "404Site", url: "http://404url.com/testing.php" }
];
var promiseList = [];
for(var i in sites){
var promise = $.ajax({
url: sites[i].url,
type: "GET",
dataType: "json",
async: true,
success: function(data){
if(data.Response != 'OK'){
console.log('Site ' + sites[i].name + ' Not OK');
}else{
console.log('Site ' + sites[i].name + ' OK ');
}
},
failure: function(data){
console.log('Failure for site: ' + sites[i].name);
},
error: function(){
console.log('Site ' + sites[i].name + ' Not OK');
}
});
promiseList.push(promise);
}
$.when.apply($, promiseList).then(function(){console.log('success')}, function(){console.log('fail')});
}
在控制檯中我看到:
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
fail
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
Site 404Site Not OK
注意,網站名稱是始終顯示爲最後一個在名單上。
請詳細說明一下,當你刪除異步什麼是不工作:假的設置。 –
你有沒有考慮過異步運行(''async:true'')? – Crowes
我不認爲上面的代碼真的有效...... * else *在函數之外。 – Robert