如何使用JavaScript每10秒检查一次状态



我有一个服务器(mysite.com/status),它返回活动任务的数量(只是一个整数)。如何使用JavaScript检查每10秒活动任务的数量,并向用户显示如下内容:

剩余任务数:XXX

并且,如果任务数为0,那么我应该加载另一个页面

设置一个调用自己的新超时

function checkTasks(){
    // Make AJAX request
    setTimeout(checkTasks, 10000);
}
checkTasks(); // Start task checking

使用jQuery实现AJAX功能…(未测试的代码)

setInterval(function(){
  $.get('http://example.com/status',function(d){
    // where there is html element with id 'status' to contain message
    $('#status').text('Number of remaining tasks: '+d)
    if(d == 0){
      window.location = '/another/page'
    }
  })
},10000)

我想到了不同的方法,没有任何AJAX。因为你只需要显示简单的普通数据,只需要使用<iframe>来显示动态数据,然后用简单的JS每10秒"重新加载"帧。

HTML应该是:

Number of remaining tasks: <iframe id="myFrame" src="mysite.com/status"></iframe>

和JavaScript:

window.onload = function() {
    window.setTimeout(ReloadTime, 10000);
};
function ReloadTime() {
    var oFrame = document.getElementById("myFrame");
    oFrame.src = oFrame.src;
    window.setTimeout(ReloadTime, 10000);
}

实时测试用例,使用相同示例的时间。

使用一些CSS,你可以使框架看起来像文本的一部分,只需要设置固定的宽度和高度,并删除边框。

 setInterval(function(elem){     // here elem is the element node where you want to display the message
        var status=checkStatus();  // supposing that the function which returns status is called checkStatus
        if(status == 0){
          window.location = '/another/page'
        }
        else {
         elem.innerHTML="Number of remaining tasks:"+status;
        }
    },10000)

使用javascript库jquery,你可以设置一个重复的无限循环。它从页面中获取数据,然后设置元素的内部html。

http://jsfiddle.net/cY6wX/14/此代码未经测试

edit:演示已更新此外,我没有使用jquery选择器来设置值,以防您不想使用jquery

最新更新