自动刷新页面

Refresh Page Automatically

本文关键字:刷新      更新时间:2024-01-12

我将创建一个JQuery幻灯片放映,但需要每5分钟刷新一次页面来更改内容。

我知道我可以通过一些Javascript来做到这一点,但这可以在客户端进行更改,以避免页面刷新。服务器是否有方法使页面超时并强制刷新?

除了javascript重载,您还可以发送一个刷新头:

header("Refresh: 300;url='http://thepage.com/example'");

无论javascript如何,浏览器都会在300秒后重定向。它可以在浏览器的配置中被禁用,但通常不会被禁用。

元刷新将非常简单地工作:

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

300意味着它将每300秒或5分钟刷新一次。通过这种方式,您不使用JavaScript,因此用户无法关闭它。

您无法强制从服务器重新加载页面。

在JavaScript中实现这一点的方法很简单:

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

尽管这可以在客户端覆盖,但reguler用户不会干扰您的脚本。


顺便说一句:你为什么如此坚定地重新加载页面?

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>

使用PHP

我会使用一个php函数,它可以在任何页面上调用,而无需设置url

    // 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);