Javascript 自动刷新页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11604261/
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
Refresh Page Automatically
提问by Somk
I will be creating a JQuery slide show, but need the page to refresh every 5 minutes to change the content.
我将创建一个 JQuery 幻灯片,但需要每 5 分钟刷新一次页面以更改内容。
I know I can do this via some Javascript, but this can be altered on the client side to avoid page refreshes. Is there a way for the server to timeout a page and force a refresh?
我知道我可以通过一些 Javascript 来做到这一点,但这可以在客户端进行更改以避免页面刷新。服务器有没有办法让页面超时并强制刷新?
回答by Esailija
In addition to a javascript reload, you can send a refresh header:
除了 javascript 重新加载之外,您还可以发送刷新标头:
header("Refresh: 300;url='http://thepage.com/example'");
The browser will redirect after 300 seconds regardless of javascript. It can be disabled in configuration of the browser though, but it's not commonly disabled.
浏览器将在 300 秒后重定向,而不管 javascript。虽然可以在浏览器的配置中禁用它,但它通常不会被禁用。
回答by Esailija
Meta refresh will work very simply:
元刷新将非常简单地工作:
<meta http-equiv="refresh" content="300">
The 300 means it will refresh every 300 seconds or 5 minutes. In this way you don't use JavaScript so there is no way the user can turn it off.
300 表示它将每 300 秒或 5 分钟刷新一次。通过这种方式,您不使用 JavaScript,因此用户无法将其关闭。
回答by Joseph Silber
There's no way you can forcethe page to reload from the server.
您无法强制页面从服务器重新加载。
The way to do it in JavaScript is simple:
在 JavaScript 中执行此操作的方法很简单:
setTimeout(function() {
window.location.reload();
}, 5000);
Although this could be overridden on the client side, reguler users won't be messing around with your script.
尽管这可能会在客户端被覆盖,但是reguler 用户不会弄乱你的脚本。
As a side note:Is there any reason you're so adamanton reloading the page?
作为旁注:您是否有任何理由如此坚持重新加载页面?
回答by Muhammed Nigil
The JavaScript Method
JavaScript 方法
var timer = null;
function auto_reload()
{
window.location = 'http://domain.com/page.php';
}
<body onload="timer = setTimeout('auto_reload()',10000);">
回答by Muhammed Nigil
The META Tag Method
META 标记方法
The following refreshes the page every 30 seconds.
<head>
<meta http-equiv="refresh" content="30" />
</head>
回答by Rob Masters
Using PHP
使用 PHP
I would use a php function that can be called on any page without having to set the url
我会使用一个可以在任何页面上调用而无需设置 url 的 php 函数
// write the function
function refresh( $time ){
$current_url = $_SERVER[ 'REQUEST_URI' ];
return header( "Refresh: " . $time . "; URL=$current_url" );
}
// call the function in the appropriate place
refresh( 4 );
// this refreshes page after 4 seconds
回答by udidu
Another way to do that reload is using window.location
:
重新加载的另一种方法是使用window.location
:
setTimeout(function(){
window.location.href = "YOUR_PAGE_URL";
}, 5000);