Javascript 自动刷新 div 内容,由 jquery 加载包括 ajax 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26991305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:35:54  来源:igfitidea点击:

Auto refresh div content, loaded by jquery include ajax call

javascriptjqueryhtmlajax

提问by AzMandius

I am loading output from now_playing.php(shoutcast now playing content) using a jQuery include ajax call, as sugested here, and it works well.

我正在now_playing.php使用 jQuery 包含 ajax 调用加载(shoutcast 现在正在播放内容)的输出,如sugested here,它运行良好。

My code:

我的代码:

<script>
$(function(){
    $("#now_playing").load("now_playing.php");
});
</script>

<div id="now_playing"></div>

I just need that div output content updated every 5 seconds or so. Which code can i add to script or div part for that? Thank you!

我只需要每 5 秒左右更新一次 div 输出内容。我可以为此将哪些代码添加到脚本或 div 部分?谢谢!

回答by Magicprog.fr

You can do this: Put your load()in a function, then use a setIntervalto call it every 5 seconds.

您可以这样做:将您load()的函数放入一个函数中,然后使用 asetInterval每 5 秒调用一次。

function loadNowPlaying(){
  $("#now_playing").load("now_playing.php");
}
setInterval(function(){loadNowPlaying()}, 5000);

回答by augustoccesar

You can use setIntervalfor that. Like

你可以用setInterval它。喜欢

setInterval(function(){
    $("#now_playing").load("now_playing.php");
    ...
}, 5000);

It'll execute the load the now_playing.phpand do the other stuff you want every 5 seconds (5000 milliseconds)

它将now_playing.php每 5 秒(5000 毫秒)执行一次加载并执行您想要的其他操作

回答by Edan Feiles

try to do it with setInterval():

尝试使用 setInterval() 来实现:

$(function(){
   setInterval(function(){$("#now_playing").load("now_playing.php")},5000);
}

回答by AzMandius

Learned Magicprog.fr, augustoccesar and Edan Feiles's suggestions, and decided Magicprog.fr's solution is best, because it first loads now_playing.php output, then just updates it at given interval:

学习了 Magicprog.fr、augustoccesar 和 Edan Feiles 的建议,并认为 Magicprog.fr 的解决方案是最好的,因为它首先加载 now_playing.php 输出,然后在给定的时间间隔更新它:

<script>
function loadNowPlaying(){
  $("#now_playing").load("now_playing.php");
}
setInterval(function(){loadNowPlaying()}, 5000);
</script>

Thank you very much for help :)

非常感谢您的帮助:)