[英]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.