如果HTML文件已更新,则执行JavaScript

我试图在JavaScript,jQuery甚至PHP中找到一个插件或函数,如果页面文件已经更新,每隔10秒检查一次,如果页面已经更新则提醒用户()。

提前谢谢:)对不起,如果我不够清楚。 如果您有任何疑问,请评论。

编辑:换句话说,使用客户端或服务器端脚本,向服务器发送AJAX请求,并确定用户打开的当前页面是否已在服务器上修改并显示警报。

您可以每10秒向服务器发送一个http HEAD请求。 这将使服务器只发送标题而不是内容。 然后你可以选择’Last-Modified’响应头。

jQuery函数$.ajax(); 支持与此非常相似的function。 而是检查Last-Modified http头jQquery使用http If-Modified-Since头向服务器发送请求。 然后它检查服务器是否响应响应代码304 Not Modified。

这是一个简短的HTML + Javascript示例,描述了jQuery的function:

       
Not Modified

但是 ,上面的jquery示例对我没有用 – 使用jQuery 1.8和firefox。(Linux)+ apache2 web服务器。 尽管服务器以304 Not Modified响应,但将调用success函数。

所以我将添加另一个实现上面第一个建议的工作示例,这里是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'); } } }); }