How to fire AJAX request Periodically?

<meta http-equiv="Refresh" Content="5">

This script reloads or refresh the page after every 5 seconds. But I want to do it using jQuery and AJAX call. Is it possible?

165969 次浏览

您可以使用 setTimeoutsetInterval

The difference is - SetTimeout 只触发函数一次,然后必须重新设置它。 setInterval keeps triggering expression again and again, unless you tell it to stop

是的,您可以使用 JavaScriptsetTimeout()方法或者 setInterval()方法来调用您想要运行的代码。以下是使用 setTimeout 的方法:

function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}


$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});

As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

对于周期性的任务,最终可能会花费比重复间隔更长的时间(比如缓慢连接上的 HTTP 请求) ,最好不要使用 setInterval()。如果第一个请求没有完成,而您又启动了另一个请求,那么您可能会遇到这样的情况,即有多个请求消耗共享资源,从而导致相互之间资源匮乏。您可以通过等待安排下一个请求直到最后一个请求完成来避免这个问题:

// Use a named immediately-invoked function expression.
(function worker() {
$.get('ajax/test.html', function(data) {
// Now that we've completed the request schedule the next one.
$('.result').html(data);
setTimeout(worker, 5000);
});
})();

为了简单起见,我使用了成功回调来调度。这样做的缺点是,一个失败的请求将停止更新。为了避免这种情况,你可以使用完整的回调:

(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();

I tried the below code,

    function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}


$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});

在指定的时间间隔内,这个函数不能正常工作,页面没有完全加载,函数被连续调用。 最好在 executeQuery()之外的单独函数中调用 setTimeout(executeQuery, 5000);,如下所示,

function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
updateCall();
}


function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}


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

这完全按计划进行。