Php MySQL的filemtime替代方案

Php MySQL的filemtime替代方案,php,mysql,push-notification,Php,Mysql,Push Notification,我正在处理推送通知,希望在数据库发生更改时更新页面 我从以下方面得到: 更新:尝试使用委托() $(“body”).delegate(“.news”,“click”,function(){ $(“#新闻”).bjqs({ “动画”:“幻灯片”, “showmarks”:假, “showControls”:false, “旋转速度”:100, “宽度”:1800, ‘高度’:160 }); var source=neweventsource('data2.php'); source.onmess

我正在处理推送通知,希望在数据库发生更改时更新页面

我从以下方面得到:

更新:尝试使用委托()


$(“body”).delegate(“.news”,“click”,function(){
$(“#新闻”).bjqs({
“动画”:“幻灯片”,
“showmarks”:假,
“showControls”:false,
“旋转速度”:100,
“宽度”:1800,
‘高度’:160
});
var source=neweventsource('data2.php');
source.onmessage=函数(事件){
$('.bjqs').append(event.data);
};
});
是!有多种(更好的)方法:

  • websocket(最好的解决方案,但在旧浏览器或移动浏览器上不受支持)
  • 服务器发送事件(SSE)(某种轮询,但仅针对您请求的任务进行了优化)
  • 长轮询(就像您正在做的那样)
  • 闪光插座
  • 其他基于插件的套接字
  • ajax轮询
  • 我以前也发过关于它的例子

    我列出了几种运输方法。WebSocket是理想的(因为它是服务器和客户端之间唯一的双向通信),SSE是我的第二选择。您不需要
    $.getJSON
    方法。总的想法是一样的

    在服务器端(本例中为php),您可以查询数据库中的更改。将数据返回为JSON(
    JSON\u encode(data)
    可以这样做)。在客户端,您可以解码JSON(
    JSON.parse(data)
    可以做到这一点)。使用收到的数据更新页面

    只是像您这样的轮询会导致更多的开销,因为您正在对服务器执行大量请求

    SSE更多的是“我想订阅流”和“我想停止监听”。=>减少开销

    Websockets更多:“我建立了一个连接。我谈论服务器侦听。服务器谈论客户端侦听”一个全双工连接最小开销

    SSE代码示例

    客户端进入的页面(例如index.html或index.php)

    这只是一个包含以下javascript的普通html页面:

    <html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
        <script>
            //javascript:
            var source = new EventSource('data.php');
            source.onmessage = function (event) {
                //here you do the stuff with the received messages.
                //like log it to the console
                console.log(event.data);
                //or append it to div
                $('#response').append(event.data);
            };
        </script>
    </head>
    <body>
        <div id="response"></div>
    </body>
    </html>
    
    这也会给您带来问题,因为您不断地重新初始化BJQ,而且它不是用来处理动态更新内容的如果有新数据,您可以只发送数据(使用php)。检查呼叫是否返回空,如果不是,则更新:

      var source = new EventSource('data2.php');
      source.onmessage = function (event) {
        if(event.data !=""){
            $('.bjqs').html(event.data);
            $("#news").bjqs({
              'animation' : 'slide',
              'showMarkers' : false,
              'showControls' : false,
              'rotationSpeed': 100,
              'width' : 1800,
              'height' : 160
            });
        }
      };
    

    您可以计算表中的行数,然后检查行数是否已更改。

    无需深入代码,我将回答标题中的问题:

    将上次修改的列添加到表中,这有一个内置的mysql触发器,该触发器在添加或更改行时更新:

    ALTER TABLE `yourTable`
        ADD COLUMN `last_modified` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ADD INDEX (`last_modified`);
    
    然后像这样询问它

    SELECT * FROM yourTable where last_modified > ?
    

    (“?”是用上次查询的时间戳替换的pdo占位符)

    请参见OK,因此我实际上根本不需要上面的第一个代码?我不确定我是否能从你的其他评论中理解这个例子。我还需要让data.php文件获取JSON吗?现在我有四个文件:index.php,在这里我显示实际数据(添加了上面的一些代码)。getData.php,上面的代码块#2,在这里我检查data.php是否有更改。data.php,上面的代码块#1,其中我从ajax.php获取JSON输出,ajax.php是从数据库获取内容的动态文件。我甚至需要所有这些文件吗?我想这4个文件让事情变得有点复杂,但对于长时间的轮询来说是必要的。另一个好的lib是:通过简单的实现为您利用正确的传输方法我尝试了SSE,但似乎很难使用MySQL数据库中的JSON数据来实现它。我已经用我的新代码更新了帖子。我将在我的答案中添加一个SSE的代码示例。我会尽量把它弄清楚;)是的,但是我怎么能一直这样做并让它推动呢?啊,这是个好主意。如何获取上次查询的时间戳?这是您在ajax中作为参数
    getData.php?timestamp=“+timestamp
    给出的,并在获取数据时更新时间戳
    <?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    
    $url = "content.json";
    $str = file_get_contents($url);
    $data = json_decode($str, TRUE);
    //generate random number for demonstration
    //echo the new number
    echo "data: " . json_encode($data);
    
    
    ob_flush();
    ?>
    
    $sql= "SELECT title, content, submitted FROM `flex_itnews` where valid = 1 order by submitted desc";
    $query= mysql_query($sql);
    setlocale(LC_ALL, 'da_DK');
    while($result = mysql_fetch_array($query)){
        echo "data: <li><span class='date'>". strftime('%e. %B', strtotime($result['submitted'])) ."<br />kl. ". strftime('%H.%M', strtotime($result['submitted'])) ."</span><h2>" . $result['title']. "</h2><p>" . $result['content'] ."</p></li>\n";
    }
    
        <script>
          var source = new EventSource('data2.php');
          source.onmessage = function (event) {
            $('.bjqs').html(event.data);
          };
    
          $('#news').livequery(function(){
            $(this).bjqs({
              'animation' : 'slide',
              'showMarkers' : false,
              'showControls' : false,
              'rotationSpeed': 100,
              'width' : 1800,
              'height' : 160
            });
          });
    
      </script>
    
        <script>
          $("body").delegate(".news", "click", function(){
            $("#news").bjqs({
              'animation' : 'slide',
              'showMarkers' : false,
              'showControls' : false,
              'rotationSpeed': 100,
              'width' : 1800,
              'height' : 160
            });
                    var source = new EventSource('data2.php');
          source.onmessage = function (event) {
            $('.bjqs').append(event.data);
          };
          });
      </script>
    
    <html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
        <script>
            //javascript:
            var source = new EventSource('data.php');
            source.onmessage = function (event) {
                //here you do the stuff with the received messages.
                //like log it to the console
                console.log(event.data);
                //or append it to div
                $('#response').append(event.data);
            };
        </script>
    </head>
    <body>
        <div id="response"></div>
    </body>
    </html>
    
    <?php
    /* set the header first, don't echo/print anything before this header is set! Else the default headers will be set first then this line tries to set the headers and results in an error because the header is already set. */
    header("Content-Type: text/event-stream\n\n");
    
    //query the database
    $sql= "SELECT COUNT(*) FROM `messages`";
    $query= mysql_query($sql);
    $result = mysql_fetch_array($query);
    $count = $result[0];
    
    //return the data
    echo "data: " . $count. "\n";
    ?>
    
      var source = new EventSource('data2.php');
      source.onmessage = function (event) {
        $('.bjqs').html(event.data);
        $("#news").bjqs({
          'animation' : 'slide',
          'showMarkers' : false,
          'showControls' : false,
          'rotationSpeed': 100,
          'width' : 1800,
          'height' : 160
        });
      };
    
      var source = new EventSource('data2.php');
      source.onmessage = function (event) {
        if(event.data !=""){
            $('.bjqs').html(event.data);
            $("#news").bjqs({
              'animation' : 'slide',
              'showMarkers' : false,
              'showControls' : false,
              'rotationSpeed': 100,
              'width' : 1800,
              'height' : 160
            });
        }
      };
    
    ALTER TABLE `yourTable`
        ADD COLUMN `last_modified` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ADD INDEX (`last_modified`);
    
    SELECT * FROM yourTable where last_modified > ?