2

我有一个名为 getlastupdate.php 的页面,它保存有人更新数据库的最后日期和时间,当您访问该页面时,您会得到如下信息:

2013-07-23 10:43:37

我想要做的是,当我加载我的主页时,我希望 javascript 获取上述日期和时间并将其存储在 var 中,然后使用 ajax 继续检查页面'getlastupdate.php'的日期/时间并进行比较它与 var 一起使用,如果日期/时间相同,则不执行任何操作,但如果不是,则通过消息发出警报,然后将 var 更新为最后一个日期/时间。

这是我尝试过的:

 <script type="text/javascript">

var comper;
$.get('getlastupdate.php', function(comperNow) {  // comperNow is the latest date/time var
// remember the date/time in var called: comper
comper = comperNow;
}
)

function mycode() {
// keep checking this page for the date/time
$.get('getlastupdate.php', function(comperNow) {
// if comper is not the same as comperNow
if (comper!=comperNow){
// show a message to the visitor
alert('New Info Added');
// and update comper to show the date/time from comperNow
comper = comperNow;
}
}
)

tid = setTimeout(mycode, 2000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
clearTimeout(tid);
}

            </script>

谢谢!!!

4

2 回答 2

1

以下代码对我有用。我认为最大的问题是使用 setTimeout 而不是 setInterval。

var comper;
function checkComper() {
  var onResponse = function(comperNow) {  // comperNow is the latest date/time var
    //check if comper has been set / first time method is called
    if (comper === undefined) {
      comper = comperNow;
      return;
    }

    if (comper !== comperNow) {
      // show a message to the visitor
      alert('New Info Added');
      // and update comper to show the date/time from comperNow
      comper = comperNow;
    }
  };
  $.get('getlastupdate.php', onResponse);
}

var tid = setInterval(checkComper, 2000); // repeat myself
于 2013-07-23T17:54:49.960 回答
1

像这样声明var comper;全局:

var comper;
$.get('getlastupdate.php', function(comperNow) {  // comperNow is the latest date/time var
// remember the date/time in var called: comper
comper = comperNow;
}
于 2013-07-23T16:14:55.403 回答