AJAX定期检查

时间:2011-12-15 21:35:43

标签: php jquery ajax

如何每隔30秒使用AJAX检查一个文件,然后只打印结果?我更喜欢使用jQuery,但只是简单的javascript也没关系。

P.S。 我一直在寻找如何做这件事。

2 个答案:

答案 0 :(得分:2)

使用setInterval每隔X毫秒运行一次函数。

setInterval(function(){
   $.get('file', function(data){  // Use AJAX to get the file you want
      console.log(data);  // Do something with the file
   });
}, 30000); // 30000ms = 30s

答案 1 :(得分:2)

这样的事情应该会有所帮助:

function getData() {
    $.get("filepath", function (data) {
        // process data...
        console.log(data);

        // Invoke the data lookup again after 30s
        window.setTimeout(function () { 
            getData();
        }, 30000); // 30s
    });
}

然后调用循环的开始:

$(document).ready(function () {
    getData();
});