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

Ste*_*ffi 1 javascript php jquery refresh

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

在此先感谢:)抱歉,如果我不够清楚.如果您有任何疑问,请评论.

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

hek*_*mgl 7

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

jQuery函数$.ajax();支持与此非常相似的功能.而是检查Last-Modifiedhttp头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>
Run Code Online (Sandbox Code Playgroud)

但是,上面的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');
                }
            }
        }); 
    }  
Run Code Online (Sandbox Code Playgroud)