您可以每 10 秒向服务器发送一个 http HEAD 请求。这将使服务器只发送标头而不是内容。然后您可以检查“Last-Modified”响应标头。
jQuery 函数$.ajax(); 支持与此非常相似的功能。但不是检查Last-Modified http 标头 jQquery 使用http If-Modified-Since 标头向服务器发送请求。然后它会检查服务器是否以响应代码 304 Not Modified 进行响应。
这是一个简短的 HTML + Javascript 示例,描述了 jQuery 功能:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
var checkUrl="test.txt";
var firstCheck = false;
window.setInterval(checkForUpdate, 1000);
function checkForUpdate() {
$.ajax(checkUrl, {
ifModified : true,
type : 'HEAD',
success : function (response) {
if(firstCheck === false) {
firstCheck = true;
return;
}
$('#output').html('the site has been modified');
}
});
}
</script>
</head>
<body>
<div id="output">Not Modified</div>
</body>
</html>
但是,上面的 jquery 示例对我不起作用 - 使用 jQuery 1.8 和 firefox.(Linux) + apache2 Web 服务器。尽管服务器响应 304 Not Modified,但仍会调用成功函数。
所以我将添加另一个 working 示例来实现我上面的第一个建议,这里是 javascript 部分:
var checkUrl="test.txt";
window.setInterval("checkForUpdate()", 1000);
var pageLoad = new Date().getTime();
function checkForUpdate() {
$.ajax(checkUrl, {
type : 'HEAD',
success : function (response, status, xhr) {
if(firstCheck === false) {
firstCheck = true;
return;
}
// if the server omits the 'Last-Modified' header
// the following line will return 0. meaning that
// has not updated. you may refine this behaviour...
var lastModified = new Date(xhr.getResponseHeader('Last-Modified'))
.getTime();
if(lastModified > pageLoad) {
$('#output').html('the site has been modified');
}
}
});
}