当数据库中有新条目时,我想在网站上显示它(不重新加载)。最好的方法是什么?
答案 0 :(得分: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);
答案 1 :(得分:0)
ajax和带超时的递归函数
check();
function check() {
// ajax
setTimeout(check, 5000); // check every 5 seconds
}