如何以及在何处以长轮询脚本进行php查询

时间:2015-02-22 13:28:08

标签: php jquery mysql ajax

我想使用长轮询来更新像facebook这样的墙贴。

如果我在msgsrv.php中使用普通的html文字,我使用了哪个显示更改的长轮询脚本。

  

现在,我想创建一个php查询,然后添加新数据(如果找到)   数据库中。

如果我在msgsrv.php添加我的php查询它不起作用,显示所有的PHP代码。所以我认为我的查询在脚本或其他任何其他地方都不正确。

我如何以及在何处在长轮询脚本中进行php查询以在index.php中回显查询结果。

的index.php

<script type="text/javascript" src="client.js"></script>
</head><body>
<div id="response"></div>
<body>

client.js

function getContent(timestamp)
{
var queryString = {'timestamp' : timestamp};

$.ajax(
    {
        type: 'GET',
        url: '/server/server.php',
        data: queryString,
        success: function(data){
            var obj = jQuery.parseJSON(data);
            $('#response').html(obj.data_from_file);
            getContent(obj.timestamp);
            }
        }
    );
}

// initialize jQuery
$(function() {
    getContent();
});

server.php

<?php
set_time_limit(0);

$data_source_file = 'msgsrv.php';

while (true) {

// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : null;

// PHP caches file data, like requesting the size of a file, by default. clearstatcache() clears that cache
clearstatcache();
// get timestamp of when file has been changed the last time
$last_change_in_data_file = filemtime($data_source_file);

// if no timestamp delivered via ajax or msgsrv.php has been changed SINCE last ajax timestamp
if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {

    // get content of msgsrv.php
    $data = file_get_contents($data_source_file);

    // put msgsrv.php's content and timestamp of last msgsrv.php change into array
    $result = array(
        'data_from_file' => $data,
        'timestamp' => $last_change_in_data_file
    );

    $json = json_encode($result);
    echo $json;

    break;

} else {
    sleep( 1 );
    continue;
}
}
?>

msgsrv.php(此查询不起作用)

include("../db.php");
    global $dbh;
    $results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='1012' ORDER BY date DESC LIMIT 1") or die(mysqli_error($dbh));

while($rows = mysqli_fetch_assoc($results)) {
    $id = $rows['id'];
    $qazi_id = $rows['qazi_id'];
    $detail = $rows['detail'];
    $username = $rows['username'];
    //etc. all

    echo '<div id="nm">'.$username.'</div><div id="dt">'.$detail.'</div>'

0 个答案:

没有答案