长轮询数据库数据?

时间:2012-11-30 10:49:50

标签: 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. data.text
  4. 是否需要制作第四个文件来从数据库(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);
    ?>
    

1 个答案:

答案 0 :(得分:1)

我最近做了一些非常相似的事情。我确实使用了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子句,该子句从db获取比最后一个元素更新的任何项目。 $ 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);

?>
相关问题