开发者

Is it possible with javascript to find file's last modified time?

Is it possible? Now, I have done live chat, where with jquery's help I connect to .php file and check last modified time and if it is not as before, I retrieve messages. If it were possible in javascript I probably would save a开发者_运维知识库 lot of resources.

Thanks.


It's definitely possible if the server is sending an accurate Last-Modified header for that particular file:

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


Short answer: there's no way but AJAX + a server-side script (in your case, jQuery + php)

Being a client-side script, javascript gets run on the client's computer, so if the file whose m-time you want to check is on the server, then you are correct to use AJAX and a server-side script. No other way will work.

If the file whose m-time you want to check is on the client's computer, then you're out of luck. Javascript is intentionally designed to be prevented from accessing the client's files. (It can only access cookies, which are on the client's computer, however, because the browser (not any javascript) loads those into its work environment.)


Maybe HTTP ETag headers could be used to check if the page has changed. The first response contains ETag and your client uses that for the following request. Your PHP server side code would then send 304 if the page has not been modified.

http://en.wikipedia.org/wiki/HTTP_ETag

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜