【发布时间】:2013-12-07 06:36:15
【问题描述】:
如果我立即对 data.txt 文件进行更改,但如果我让浏览器静置几分钟,我的脚本就可以工作。我再次更改了data.txt文件中的内容,直到我刷新浏览器它才起作用。
index.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<meta name="robots" content="noindex, nofollow" />
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var timestamp = null;
function getMsg() {
$.ajax({
type: "GET",
url: "get.php?timestamp=" + timestamp,
async: true,
cache: false,
success: function(data) {
var json = eval('(' + data + ')');
if (json['msg'] != "") {
$(".chat").append(json['msg'], "<br>");
}
timestamp = json['timestamp'];
setTimeout('getMsg()', 1000);
}
});
}
$(document).ready(function() {
getMsg();
});
</script>
</head>
<body>
<div class="chat"></div>
</body>
</html>
get.php
<?php
$file = "data.txt";
$lastmoded = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmoded = filemtime($file);
while ($currentmoded <= $lastmoded) {
usleep(10000);
clearstatcache();
$currentmoded = filemtime($file);
}
$response = array();
$response['msg'] = file_get_contents($file);
$response['timestamp'] = $currentmoded;
echo json_encode($response);
?>
【问题讨论】:
-
json['msg'] 像 json.msg 一样使用。并添加 dataType:'json',
-
出于好奇,如果您在成功回调中删除 setTimeout 并执行
$(document).ready(function() { setInterval(getMsg, 1000); });,会发生什么情况 -
检查 php 错误日志,因为它可能有 30 秒的超时,所以如果你的 php 脚本在那段时间内没有完成它的工作,那么它就会死掉。
-
谢谢 bumbu,我相信这行得通。
-
顺便说一句,我做了类似的事情,也许这段代码可以帮助你:github.com/panique/php-long-polling
标签: php jquery html ajax long-polling