ajax长轮询不起作用,如果我听之任之


ajax long polling not working if I let sit

如果我立即更改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);
?>

尝试

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

服务器可能已经传回错误,如果您收到错误,您可以重新启动该函数

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