Jquery 如何定期触发AJAX请求?
此脚本每5秒重新加载或刷新一次页面。但是我想使用jQuery和AJAX调用来实现它。可能吗 您可以使用Jquery 如何定期触发AJAX请求?,jquery,ajax,Jquery,Ajax,此脚本每5秒重新加载或刷新一次页面。但是我想使用jQuery和AJAX调用来实现它。可能吗 您可以使用setTimeout或setInterval 区别在于—— setTimeout只触发函数一次,然后必须重新设置。 setInterval会一次又一次地触发表达式,除非您告诉它停止是,否则您可以使用JavaScript方法或setInterval()方法来调用要运行的代码。下面是使用setTimeout的方法: <meta http-equiv="Refresh" Content="5"&
setTimeout
或setInterval
区别在于——
setTimeout只触发函数一次,然后必须重新设置。
setInterval会一次又一次地触发表达式,除非您告诉它停止是,否则您可以使用JavaScript方法或
setInterval()
方法来调用要运行的代码。下面是使用setTimeout的方法:
<meta http-equiv="Refresh" Content="5">
正如其他人所指出的,setInterval和setTimeout将起到作用。我想强调一点更先进的技术,这是我从保罗·爱尔兰的精彩视频中学到的: 对于可能最终花费比重复间隔更长时间的定期任务(如低速连接上的HTTP请求),最好不要使用
setInterval()
。如果第一个请求尚未完成,而您又启动了另一个请求,那么您可能会遇到这样的情况:有多个请求消耗共享资源,并且彼此饥饿。您可以通过等待计划下一个请求直到最后一个请求完成来避免此问题:
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);
});
为简单起见,我使用成功回调进行调度。缺点是一个失败的请求将停止更新。要避免这种情况,可以使用完整回调:
// 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);
}
});
})();
在指定的时间间隔内,这没有按预期工作,页面没有完全加载,函数被连续调用。
最好调用setTimeout(executeQuery,5000)代码>外部executeQuery()
在一个单独的函数中,如下所示
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);
});
这完全符合预期。仅使用setTimeout(executeQuery,5000);而不是setTimeout('executeQuery()',5000);-它更短更快。这不是一个递归函数调用吗?如果是,那么让它一次又一次地运行很长一段时间可以吗,因为它是递归的?只要ajax保持成功执行,就可能是无限递归。因此,如果您使用setTimeout,那么有没有办法从这个代码块之外停止这个线程?就像在setInterval中一样,您可以简单地调用clearInterval()。@RahulDole这是一个好问题,但它不是递归的。它不是直接从worker函数调用的,因此堆栈不会继续增长。第二点,检查setTimeout()的文档,您将看到它返回一个数字id,可以传递给clearTimeout()。@RahulDole,如果您使用chrome play around with console.trace()查看函数的调用堆栈。setTimeout()调用的函数堆栈很短,它肯定不包括调用setTimeout()的函数。@Anupal只是创建了一个新问题。
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();
});