我运行名为像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
注意,网站名称是始终显示为最后一个在名单上。
+0
请详细说明一下,当你删除异步什么是不工作:假的设置。 –
+0
你有没有考虑过异步运行(''async:true'')? –
+0
我不认为上面的代码真的有效...... * else *在函数之外。 –