0

データベースに新しいエントリがある場合、ウェブサイトにライブで表示したい (リロードせずに)。それを行う最良の方法は何ですか?

4

2 に答える 2

1

最善の策は、ロング ポーリング (AJAX を使用して Web サーバーをポーリングする) を使用することです。このメソッドは、jQuery 経由でロング ポーリング (Comet) を使用します。

var timestamp = null;

function waitForMsg() {
    $.ajax({
        type: "POST",
        url:  "/path/to/php-script.php",
        data: { timestamp: timestamp },
        async: true,
        cache: false,
        success: function(data) {
            var json = eval('(' + data + ')');

            if(json['msg'] !== '') {
                $('#example-element').append(json['msg'] + '<br />');
            }

            timestamp = json['timestamp'];
            setTimeout(waitForMsg, 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            $('#error').html('Error: ' + textStatus + ' (' + errorThrown + ')');
            setTimeout(waitForMsg, 15000);
        }
    });
}

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

PHP は次のようになります。

$filename = 'text_file.txt'; // Replace this with a "$query" if using a db
$lastmod  = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
$currmod  = filemtime($filename);

while($currmod <= $lastmod) {
    usleep(10000);
    clearstatcache();
    $currmod = filemtime($filename);
}

$response = array();
$response['msg'] = file_get_contents($filename); // Or run your db query here
$response['timestamp'] = $currmod;

echo json_encode($response);
于 2012-08-09T23:44:07.070 に答える
0

ajax とタイムアウト付きの再帰関数

check();

function check() {

    // ajax

    setTimeout(check, 5000); // check every 5 seconds
}
于 2012-08-09T23:43:56.773 に答える