立即通过AJAX重新加载div,然后每5秒重新加载一次div [英] Reload a div via AJAX immediately and then every 5 seconds

查看:77
本文介绍了立即通过AJAX重新加载div,然后每5秒重新加载一次div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每5秒重新加载 div 。为此,我在网上发现了一个有效的脚本。唯一的问题是文件的第一次加载是在5秒之后,但我希望第一次加载是立即的。这可能是一件小事,但我之前从未使用过Javascript。谢谢!

I want to reload a div every 5 seconds. For this I found a script online which works. The only issue is that the first load of the file is after 5 seconds, but I want to first one to be immediately. It's probably a minor thing but I have never worked with Javascript before. Thank you!

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    function autoRefresh_div() {
        $("#div").load("load.html");
    }
    setInterval('autoRefresh_div()', 5000);
</script>


推荐答案

您需要设置间隔计时器然后调用功能直接。试试这个:

You need to setup the interval timer and then call the function directly. Try this:

function autoRefresh_div() {
    $("#div").load("load.html");
}
setInterval(autoRefresh_div, 5000); // every 5 seconds
autoRefresh_div(); // on load

另请注意,最好使用链接请求setTimeout(),而不是排队。这是因为如果服务器变慢,或者在请求中陷入困境,您将不会继续将它们打包,因为下一个请求仅在前一个请求完成后触发。试试这个:

Also note that it's better practice to chain the requests using setTimeout(), rather than queue them. This is because if the server slows, or gets bogged down in requests you won't keep piling them on, as the next request only fires after the previous one completes. Try this:

function autoRefresh_div() {
    $("#div").load("load.html", function() {
        setTimeout(autoRefresh_div, 5000);
    });
}

autoRefresh_div();

这篇关于立即通过AJAX重新加载div,然后每5秒重新加载一次div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆