【问题标题】:The best way to show new entry when there's a new entry in a database [closed]当数据库中有新条目时显示新条目的最佳方式[关闭]
【发布时间】:2012-08-09 23:38:10
【问题描述】:

当数据库中有新条目时,我想在网站上实时显示(无需重新加载)。最好的方法是什么?

【问题讨论】:

  • 使用 ajax 请求并根据最后出现在站点日期或 ID 上选择最新条目...
  • 好吧,“无需重新加载”基本上归结为某种形式的“AJAX”——XHR(拉)、iframe(拉)、XHR/comet(推),甚至 Flash/SL 等。除此之外,这个问题实在是太模糊了,不够精炼。

标签: php javascript mysql live


【解决方案1】:

最好的办法是使用长轮询(使用 AJAX 轮询 Web 服务器)。此方法通过 jQuery 使用长轮询(彗星):

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

【讨论】:

  • 请不要将字符串传递给setTimeout/setInterval。没有必要。 setTimeout(waitForMsg, 15000); 将在这里工作(并且将避免全局破坏或在“全局范围”中没有 waitForMsg)。
  • @pst 测试了您的建议,它仍然有效。已修复,谢谢。
【解决方案2】:

ajax 和带有超时的递归函数

check();

function check() {

    // ajax

    setTimeout(check, 5000); // check every 5 seconds
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-02
    • 2021-06-18
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2014-10-14
    • 2015-02-08
    相关资源
    最近更新 更多