<meta http-equiv="Refresh" Content="5">
此脚本每隔5秒重新加载或刷新页面。但是我想使用jQuery和AJAX调用来实现。有可能吗?
发布于 2011-02-20 02:22:52
正如其他人指出的那样,setInterval和setTimeout将会做到这一点。我想强调一点更高级的技术,这是我从保罗·爱尔兰的这段优秀视频中学到的: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);
});
})();
为了简单起见,我使用了success回调来进行调度。这样做的缺点是一个失败的请求将停止更新。为了避免这种情况,您可以使用完整的回调:
(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);
}
});
})();
发布于 2011-02-20 02:14:00
可以,您可以使用JavaScript setTimeout()
方法或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);
});
发布于 2011-02-20 02:08:18
您可以使用setTimeout
或setInterval
。
不同的是- setTimeout只触发函数一次,然后您必须再次设置它。setInterval一次又一次地触发表达式,除非您告诉它停止
https://stackoverflow.com/questions/5052543
复制相似问题