是否可以使用javascript查找文件的上次修改时间?

goo*_*ing 2 javascript php jquery

可能吗?现在,我已经进行了实时聊天,在jquery的帮助下,我连接到.php文件并检查上次修改时间,如果不是以前,我检索消息.如果有可能在javascript中我可能会节省大量资源.

谢谢.

chj*_*hjj 12

如果服务器正在为该特定文件发送准确的Last-Modified标头,那肯定是可能的:

var getMTime = function(url, callback) {
  var xhr = XMLHttpRequest();
  xhr.open('HEAD', url, true); // use HEAD - we only need the headers
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var mtime = new Date(xhr.getResponseHeader('Last-Modified'));
      if (mtime.toString() === 'Invalid Date') {
        callback(); // dont want to return a bad date
      } else {
        callback(mtime);
      }
    }
  }
  xhr.send();
};

getMTime('url here', function(mtime) {
  if (mtime) console.log('the mtime is:' + mtime.toISOString());
});
Run Code Online (Sandbox Code Playgroud)