如何在我的长轮询中使用我的php文件

时间:2014-12-26 15:50:14

标签: php jquery

我正在使用来自https://github.com/panique/php-long-polling的漫长投票脚本,效果很好。

在这个脚本中,他们使用文本文件来获取新数据。

问题1:如何在此server.php文件中使用update.php instant data.txt来获取数据?

问题2:我的update.php文件是否具有正确的格式来显示数据?

//I was tried this in server.php file but not show anything
$data_source_file = 'update.php';

server.php

set_time_limit(0);

$data_source_file = 'data.txt';

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();

$last_change_in_data_file = filemtime($data_source_file);

if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {

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

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

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

    break;

    } else {
        // wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
        sleep( 1 );
        continue;
    }
}

update.php

$u = mysqli_query($dbh,"SELECT * FROM updateside WHERE `parent_id`='".$parent."' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
while ($row = mysqli_fetch_array($u)) {
$parent_id = $row['parent_id'];
$sub = $row['sub'];
$detail = $row['detail'];

echo '<div class="upbox" id="'.$parent_id.'">
// All result of above query
Subject:'.$sub.' <br>
Detail: '.$detail.'
</div>';
}

Clint.js

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

    $.ajax(
        {
        type: 'GET',
        url: 'http://myweb.com/server/server.php',
        data: queryString,
        success: function(data){
            // put result data into "obj"
            var obj = jQuery.parseJSON(data);
            // put the data_from_file into #response
            $('#response').html(obj.data_from_file);
            // call the function again, this time with the timestamp we just got from server.php
            getContent(obj.timestamp);
            }
        }
    );
}

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

0 个答案:

没有答案