无法实施长轮询

时间:2015-02-23 12:08:51

标签: php jquery mysql ajax

我是关于长期民意调查的新手。如果数据库中有任何新数据,我想更新我的墙。所以作为一个小字段,我只是尝试下面的脚本,在index.php页面中连续显示undefined

我在server.php on test中使用了这段代码,效果很好。

while (true) {
    $random = rand(1, 10); 
    $data = ($random == 1) ? array('aaa' => time()) : array();
    if (!empty($data)) {
        echo json_encode($data);
        flush();
        exit(0);
    }
    sleep(5);
}

在这里,当我要实现我的php query时,我的问题就出现了。 我根本不知道如何做到这一点。

如何在server.php文件中进行查询并在长时间轮询中回显它的数据?

我读了很多关于长期民意调查的文章,但在我的案例中找不到任何好的例子。

我在index.php中的jQuery

        function fetch() {
            $.ajax({
                url: 'http://bdshowbiz.com/server/server.php',
                async: true,
                type: 'get',
                dataType: 'json',
                success: function(ret, textStatus, jqXHR) {
                    $('#response').append('<p>' + ret.aaa + '</p>');
                    fetch();
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    setTimeout(fetch, 5000);
                }
            });
        }
        $(function(){
            fetch();
        });

实现查询后的当前server.php文件(可能是错误的方式)

include("../db.php");
global $dbh;
header('Content-Type: application/json; charset=utf-8');
while (true) {
    //fetch data
    $results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='1012' ORDER BY date DESC LIMIT 1") or die(mysqli_error($dbh));
    $rows =  mysqli_fetch_assoc($results);
    $data = $rows['description'];

    if (!empty($data)) {
        echo json_encode($data);
        flush();
        exit(0);
    }
    sleep(5);
}

0 个答案:

没有答案
相关问题