php - 对数据库数据进行长轮询?

标签 php jquery mysql ajax long-polling

经过一周的谷歌搜索和搜索。我什至很难找到关于从数据库表而不是从名为 data.text 的纯文本文件进行长轮询的教程。目前,我在 data.text 中手动编写任何内容,它会立即出现在浏览器中。

问题是:使用数据库进行长轮询?即使在 StackOverflow 中也没有正确回答。 (我在这里找到了很多,但都是徒劳的。)。这方面的例子也在这里 filemtime alternative for MySQL

如何修改 getdata.php 使其能够从数据库中获取数据?

 $sql=mysqli_query($database,"SELECT * FROM messages  where time>=$curr_date ORDER by      time DESC");
  while($row=mysqli_fetch_array($sql)){
    $messages=$row['messages'];
    $id=$row['id'];
    echo $messages;
  }

消息表如下

    id     fro   to  mesg      time  status  last_modified  

我在这里列出一个例子。 在此示例中,使用了三个文件。

  1. index.html
  2. getdat.php
  3. 数据.文本

是否需要制作第四个文件来从数据库(mysql)中获取数据?如果不是,那么需要对 getdata.php 或 data.text 进行哪些类型的更改才能使用来自数据库的动态数据?

这是我的Javascript

<script type="text/javascript" charset="utf-8">

        var timestamp = null;

        function waitformsg() {
            $.ajax({
                type:"Post",
                url:"getdata.php?timestamp="+timestamp,
                async:true,
                cache:false,
                success:function(data) {
                    var json = eval('(' + data + ')');
                    if(json['msg'] != "") {
                        $("#messages").append(json['msg']);

                    }
                    timestamp = json["timestamp"];

                    setTimeout("waitformsg()", 1000);
                },
                error:function(XMLhttprequest, textstatus, errorthrown) {
                    alert("error:" + textstatus + "(" + errorthrown + ")");
                    setTimeout("waitformsg()", 15000);
                }




                });

        }
        $(document).ready(function() {

            waitformsg();
        });
    </script>

这里是getdata.php文件

<?php
include("../model/includes/classes.php");

$filename='data.php';

$lastmodif=isset($_GET['timestamp'])?$_GET['timestamp']:0;
$currentmodif=filemtime($filename);

while($currentmodif<=$lastmodif){
    usleep(10000);
    clearstatcache();
    $currentmodif=filemtime($filename);
}

$response=array();
$response['msg']=file_get_contents($filename);
$response['timestamp']=$currentmodif;
echo json_encode($response);
?>

最佳答案

我最近做了一些非常相似的事情。我确实使用了 jQuery .ajax 调用而不是通用的 XMLhttprequest,但想法是一样的:

recentFunction(container, lastDate){
    var lastDate = "";

    return $.ajax({
        type: "POST",
        url: "getData.php",
        cache: false,
        data: { 'request': 'recent',
            'param': lastDate },
        dataType: "json",
        success: function(data){
            if(data != null){
                $.each(data, function(key, value){
                    if(key == 0){
                        lastDate = value['date_added'];
                    }
                    var html = "some html here";
                    // append html to dom element here
                                // and delete any old items here if needed
                });
            }
        },
        complete: function(){
            setTimeout(function(){recentFunction(container, lastDate)}, 7000);
        }
    });
}

getData.php 文件中,我使用 where 子句进行查询,该子句从数据库中获取比最后一个元素更新的任何项目。 $lastDate 的默认值设置为 0,因此如果没有提交日期,它会返回所有项目。

<?php

$lastDate = 0;
$recent = array();
$recentQuery = "SELECT id, date FROM someTable WHERE date > '" . $lastDate . "'";
$recentResults = $db->query($recentQuery);

while($r = $recentResults->fetch_array(MYSQLI_ASSOC)){
      $recentMovies[] = $r;
}

echo json_encode($recentMovies);

?>

关于php - 对数据库数据进行长轮询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13643713/

相关文章:

php - SQL查询只打印第一行

php - addslashes(stripslashes($field)) 能保证sql注入(inject)无漏洞吗?

c# - 从 ajax 调用填充多个下拉列表

mysql - 为什么htop列出这么多mysql连接?

关于引用完整性规则的 MySQL 删除表

php - 将当前日期时间与数据库中的日期时间进行比较,无需刷新页面

php - 通过 PHP 将 mysql 列更新为 NULL 不起作用

javascript - 使用 jQuery 可排序(不是表单)的 AJAX 发布附加数据

javascript - 在页面加载时启动 Bootstrap 模态,具体取决于上一页按钮的单击情况

mySQL - 在匹配查询之前和之后查找项目