简体   繁体   English

每 30 秒自动刷新页面

[英]Auto refresh page every 30 seconds

I have a JSP page which has to display the status of various jobs that are running.我有一个 JSP 页面,它必须显示正在运行的各种作业的状态。 Some of these jobs take time, so it takes a while for their status to change from processing to complete.其中一些作业需要时间,因此它们的状态从处理变为完成需要一段时间。

Is it a good idea to have a javascript function that would refresh the page every 30 seconds or so?拥有一个每隔 30 秒左右刷新一次页面的 javascript 函数是个好主意吗? Are there any ramifications for having a script that is constantly refreshing a page?拥有不断刷新页面的脚本是否有任何后果?

The other option is to have a refresh button which on click would refresh the page.另一种选择是有一个刷新按钮,点击它会刷新页面。

There are multiple solutions for this.对此有多种解决方案。 If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta tag in your head tag.如果您希望刷新页面,您实际上不需要 JavaScript,如果您在head标记中添加此meta标记,浏览器可以为您完成。

<meta http-equiv="refresh" content="30">

The browser will then refresh the page every 30 seconds.然后浏览器将每 30 秒刷新一次页面。

If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with Location.reload() ( docs ) inside a setTimeout() :如果你真的想用 JavaScript 来做,那么你可以在setTimeout()使用Location.reload() ( docs ) 每 30 秒刷新一次页面:

window.setTimeout(function () {
  window.location.reload();
}, 30000);

If you don't need to refresh the whole page but only a part of it, I guess an AJAX call would be the most efficient way.如果您不需要刷新整个页面而只需要刷新其中的一部分,我想 AJAX 调用将是最有效的方式。

Just a simple line of code in the head section can refresh the page只需在head部分简单的一行代码就可以刷新页面

<meta http-equiv="refresh" content="30">

although its not a javascript function, its the simplest way to accomplish the above task hopefully.虽然它不是一个 javascript 函数,但它是有希望地完成上述任务的最简单方法。

Use setInterval instead of setTimeout .使用setInterval而不是setTimeout Though in this case either will be fine but setTimeout inherently triggers only once setInterval continues indefinitely.尽管在这种情况下两者都可以,但setTimeout仅在setInterval无限期继续时固有地触发。

<script language="javascript">
setInterval(function(){
   window.location.reload(1);
}, 30000);
</script>

If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.如果你想刷新页面你可以这样使用,但刷新页面通常不是最好的方法,最好尝试只更新你需要更新的内容。

javascript: javascript:

<script language="javascript">
setTimeout(function(){
   window.location.reload(1);
}, 30000);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM