1

我们如何实现一个计时器来发送一个 ajax 请求以每分钟刷新一次数据(例如来自数据库上其他用户的新条目)。我正在使用来自 jquery 的 $.ajax。

我的目的是发送最后一次更新的时间,这样服务器就不会发送重复的数据。只有在那之后创建的行。

我的服务器脚本是 php。

4

2 回答 2

2

发送日期和时间您可以使用此功能

        var date    = new Date();
        var date    = date.getUTCFullYear() + '-' +
        ('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
        ('00' + (date.getUTCDate()).slice(-2) + ' ' + 
        ('00' + date.getUTCHours()).slice(-2) + ':' + 
        ('00' + date.getUTCMinutes()).slice(-2) + ':' + 
        ('00' + date.getUTCSeconds()).slice(-2);

上面将以mysql格式格式化日期和时间,您通过变量将其传递给mysql查询,然后setInterval在每分钟后用于传递当前时间

    setInterval(function(){ 
     $.ajax({
     type:"POST",
     data:"Time="+ date,     
     url:"serverRef",
     success: function(data){
         // On success 
                           }
     });              

     },60000);

注意:您也可以在服务器端使用相同的技术

于 2013-04-07T20:25:35.477 回答
1

setInterval with jQuery's post would work wonders. Make sure if you have a lot of visitors, remember to cache, otherwise you can rack up a lot of queries without noticing, which in the past I've noticed can overwhelm some hosts and essentially take you offline.

var ajax = window.setInterval(function(){
    $.post('path/to/my/script.php', function(data){
         if(data == "stop")
         {
             clearInterval(ajax);
             return;
         }

         $('#statistics').html(data);
    });
}, 60000);
于 2013-04-07T20:31:13.487 回答