如果我立即更改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);
?>
答案 0 :(得分:0)
尝试
var timestamp = null;
$(document).ready(function() {
getMsg();
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);
}
});
}
});
答案 1 :(得分:0)
服务器可能已经返回错误,如果出现错误,可以重新启动该功能
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);
},
error: function(){
setTimeout('getMsg()', 1000);
}
});
}