开发者

Monitor file change through AJAX, how?

I'm looking for a way through AJAX (not via a JS framework!) to real time monitor a file for changes. If changes where made to that file, I need it to give an alert message. I'm a total AJAX noob, so please be gentl开发者_如何学Ce. ;-)

Edit: let me explain the purpose a bit more in detail. I'm using a chat script I've written in PHP for a webhop, and what I want is from an admin module monitor the chat requests. The chats are stored in text files, and if someone starts a chat session a new file is created. If that's the case, in the admin module I want to see that in real time.

Makes sense?


To monitor a file for changes with AJAX you could do something like this.

var previous = "";

setInterval(function() {
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4) {
            if (ajax.responseText != previous) {
                alert("file changed!");
                previous = ajax.responseText;
            }
        }
    };
    ajax.open("POST", "foo.txt", true); //Use POST to avoid caching
    ajax.send();
}, 1000);

I just tested it, and it works pretty well, but I still maintain that AJAX is not the way to go here. Comparing file contents will be slow for big files. Also, you mentionned no framework, but you should use one for AJAX, just to handle the cross-browser inconsistencies.


AJAX is just a javascript, so from its definition you do not have any tool to get access to file unless other service calls an js/AJAX to notify about the change.


I've done that from scratch recently.

I don't know how much of a noob you are with PHP (it's the only server script language I know), but I'll try to be as brief as possible, feel free to ask any doubt.

I'm using long polling, which consists in this (

  1. Create a PHP script that checks the content of the file periodically and only responds when it sees any change (it could include a description of the change in the response)
  2. Create your XHR object
  3. Include your notification code as a callback function (it can use the description)
  4. Make the request
  5. The PHP script will start checking the file, but won't reply until there is a change
  6. When it responds, the callback will be called and your notification code will launch

If you don't care about the content of the file, only that it has been changed, you can check the last-modified time instead of the content in the PHP script.

EDIT: from some comment I see there's something to monitor file changes called FAM, that seems to be the way to go for the PHP script

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜