我将创建一个 JQuery 幻灯片放映,但需要每 5 分钟刷新一次页面以更改内容。
我知道我可以通过一些 Javascript 来做到这一点,但这可以在客户端进行更改以避免页面刷新。服务器有没有办法让页面超时并强制刷新?
我将创建一个 JQuery 幻灯片放映,但需要每 5 分钟刷新一次页面以更改内容。
我知道我可以通过一些 Javascript 来做到这一点,但这可以在客户端进行更改以避免页面刷新。服务器有没有办法让页面超时并强制刷新?
除了 javascript 重新加载之外,您还可以发送刷新标头:
header("Refresh: 300;url='http://thepage.com/example'");
浏览器将在 300 秒后重定向,不管 javascript。虽然可以在浏览器的配置中禁用它,但通常不会禁用它。
元刷新将非常简单:
<meta http-equiv="refresh" content="300">
300 表示它将每 300 秒或 5 分钟刷新一次。通过这种方式,您不使用 JavaScript,因此用户无法将其关闭。
您无法强制页面从服务器重新加载。
在 JavaScript 中执行此操作的方法很简单:
setTimeout(function() {
window.location.reload();
}, 5000);
尽管这可以在客户端被覆盖,但调节器用户不会弄乱你的脚本。
作为旁注:您有什么理由如此坚持重新加载页面?
JavaScript 方法
var timer = null;
function auto_reload()
{
window.location = 'http://domain.com/page.php';
}
<body onload="timer = setTimeout('auto_reload()',10000);">
META标签方法
The following refreshes the page every 30 seconds.
<head>
<meta http-equiv="refresh" content="30" />
</head>
我会使用可以在任何页面上调用而无需设置 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
另一种重新加载的方法是使用window.location
:
setTimeout(function(){
window.location.href = "YOUR_PAGE_URL";
}, 5000);