[英]Ajax jquery - instant load
I have a live updating div on my website. 我的网站上有一个实时更新的div。 It works fine however the user always have to wait 5 seconds before it loads. 它工作正常,但是用户始终需要等待5秒钟才能加载。 Heres my code: 这是我的代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#div-id').load('/something.php');
}, 5000);
});
</script>
Is there a way I can load, it then wait 5 seconds and load it again? 有什么方法可以加载,然后等待5秒钟再加载一次? Instead of wait 5 seconds, load it, then wait again... 无需等待5秒钟,而是加载它,然后再次等待...
Thanks 谢谢
Yes. 是。 jQuery's load()
method has a complete callback function as a parameter: jQuery的load()
方法具有完整的回调函数作为参数:
.load( url [, data ] [, complete ] )
complete 完成
A callback function that is executed when the request completes. 请求完成时执行的回调函数。
Thanks to this we can create a recursive function which calls itself once complete (or in this case, after 5 seconds): 多亏了这一点,我们可以创建一个递归函数,该函数在完成后(或在这种情况下,需要5秒钟)自动调用:
function loadContent(selector, path) {
$(selector).load(path, function() {
setTimeout( loadContent(selector, path), 5000 );
});
}
loadContent('#div-id', '/something.php');
What I've done here is move your content loading logic into a new function called loadContent
, which accepts a selector and a path as its parameters. 我在这里所做的就是将您的内容加载逻辑移动到名为loadContent
的新函数中,该函数接受选择器和路径作为其参数。 This function then triggers load()
on the passed in selector, loading the passed in path. 然后,此函数在传入的选择器上触发load()
,加载传入的路径。 When the content has loaded a setTimeout
function kicks in to trigger our loadContent
function once again after 5000 millisecond (5 seconds). 内容加载loadContent
后,将在5000毫秒(5秒)后启动setTimeout
函数以再次触发我们的loadContent
函数。
Triggering loadContent()
to begin with will fire our function off immediately, meaning you will not have to wait 5 seconds before the content first loads. 触发loadContent()
开始将立即触发我们的功能,这意味着您无需等待5秒钟即可首次加载内容。
You have to run your ajax manually before first interval run. 在第一次运行间隔之前,您必须手动运行ajax。
<script type="text/javascript">
var loadContent = function() {
$('#div-id').load('/something.php');
};
$(document).ready(function() {
$.ajaxSetup({ cache: false });
loadContent();
setInterval(loadContent, 5000);
});
</script>
Just call the load
once before 只需一次调用load
$('#div-id').load('/something.php');
setInterval(function() {
$('#div-id').load('/something.php');
}, 5000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.