[英]using SetTimeout with Ajax calls
我试图使用setTimeout来检查表中是否存在数据:
如果数据存在则不获取数据。 如果数据不存在,则使用load获取数据,然后每隔x分钟执行相同的操作。
这是我到目前为止所拥有的。 由于某种原因,当它触及If块时, setTimeout
不起作用。
我甚至不确定这是否是最好的方法。
var sTimeOut = setTimeout(function () {
$.ajax({
url: 'CheckIfDataExists/' +
new Date().getTime(),
success: function (response) {
if (response == 'True') {
$('.DataDiv')
.load('GetFreshData/' + new Date()
.getTime(), { "Id": $("#RowID").val() });
}
},
complete: function () {
clearTimeout(sTimeOut);
}
});
}, 10000);
任何帮助将不胜感激。
更新 ...
setTimeout(function(){checkData()}, 5000);
function checkData(){
$.ajax({
url: 'CheckIfDataExists/' +
new Date().getTime(),
success: function (response) {
if (response == 'True') {
$('.DataDiv')
.load('GetFreshData/' + new Date()
.getTime(), { "Id": $("#RowID").val() });
} else {
$('.OutOfWindow').html('No Data Found');
setTimeout(function () { checkData() }, 5000);
}
},
complete: function () {
// clearTimeout(sTimeOut);
}
});
}
这样的东西应该工作,第一个片段是本地化的,所以我可以测试运行它。 我已经解释了代码,下面是代码应该是什么
就像你意识到的那样(从帖子上的更新开始), setTimeout
只调用你的目标函数一次 ,所以要继续检查你需要再次调用它,如果你做了一个失败的检查。
在JsFiddle上看到它: http : //jsfiddle.net/jQxbK/
//we store out timerIdhere
var timeOutId = 0;
//we define our function and STORE it in a var
var ajaxFn = function () {
$.ajax({
url: '/echo/html/',
success: function (response) {
if (response == 'True') {//YAYA
clearTimeout(timeOutId);//stop the timeout
} else {//Fail check?
timeOutId = setTimeout(ajaxFn, 10000);//set the timeout again
console.log("call");//check if this is running
//you should see this on jsfiddle
// since the response there is just an empty string
}
}
});
}
ajaxFn();//we CALL the function we stored
//or you wanna wait 10 secs before your first call?
//use THIS line instead
timeOutId = setTimeout(ajaxFn, 10000);
您的代码应如下所示:
var timeOutId = 0;
var ajaxFn = function () {
$.ajax({
url: 'CheckIfDataExists/' + new Date().getTime(),
success: function (response) {
if (response == 'True') {
$('.DataDiv').
load('GetFreshData/' + new Date().
getTime(), { "Id": $("#RowID").val() });
clearTimeout(timeOutId);
} else {
timeOutId = setTimeout(ajaxFn, 10000);
console.log("call");
}
}
});
}
ajaxFn();
//OR use BELOW line to wait 10 secs before first call
timeOutId = setTimeout(ajaxFn, 10000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.