mki*_*o76 10 javascript jquery asp.net-mvc-3
我试图使用setTimeout来检查表中是否存在数据:
如果数据存在则不获取数据.如果数据不存在,则使用load获取数据,然后每隔x分钟执行相同的操作.
这是我到目前为止所拥有的.出于某种原因,setTimeout当它命中If块时不起作用.
我甚至不确定这是否是最好的方法.
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);
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
更新 ...
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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
gid*_*eon 21
这样的东西应该工作,第一个片段是本地化的,所以我可以测试运行它.我已经解释了代码,下面是代码应该是什么
就像你意识到的那样(从你在帖子上的更新)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);
Run Code Online (Sandbox Code Playgroud)
您的代码应如下所示:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58182 次 |
| 最近记录: |