2012-09-19 49 views
12

我有一个页面在10秒后用下面的代码重定向用户。重定向10秒倒计时

<META HTTP-EQUIV="refresh" CONTENT="10;URL=login.php"> 

然后我有这样的代码,其在PHP回显,并将会像“10”(秒)动态倒数为10,如图9所示,8个,7 ...所以用户可以看到直到页面重定向的秒数。

echo "We cant find you on the system. <br/> Please return to the <b><a href='login.php'>Login</a></b> page and ensure that <br/>you have entered your details correctly. 
<br> 
<br> 
<b>Warning</b>: You willl be redirected back to the Login Page <br> in <b>10 Seconds</b>"; 

我,想知道是否有一种方式,这可以在PHP做如果不是会有什么来达到同样的最佳方式?

回答

34

下面将用户重定向马上login.php

<?php 
header('Location: login.php'); // redirects the user instantaneously. 
exit; 
?> 

您可以使用以下方法来延缓重定向X秒,但没有图形倒计时(感谢user1111929):

<?php 
header('refresh: 10; url=login.php'); // redirect the user after 10 seconds 
#exit; // note that exit is not required, HTML can be displayed. 
?> 

如果你想有一个图形倒计时,这里是一个JavaScript示例代码:

<p>You will be redirected in <span id="counter">10</span> second(s).</p> 
<script type="text/javascript"> 
function countdown() { 
    var i = document.getElementById('counter'); 
    if (parseInt(i.innerHTML)<=0) { 
     location.href = 'login.php'; 
    } 
    i.innerHTML = parseInt(i.innerHTML)-1; 
} 
setInterval(function(){ countdown(); },1000); 
</script> 
+0

有没有什么办法可以在echo语句中使用“10”动态计数? 10,9,8,7 ..?谢谢 – user1662306

+1

不,那不可能。只需使用我提供给您的javascript解决方案。然后使用Jquery做一个动态的倒计时。 – TimTastic

+0

将研究。感谢您的意见 – user1662306

8

我会用JavaScript来此

var counter = 10; 
setInterval(function() { 
    counter--; 
    if(counter < 0) { 
     window.location = 'login.php'; 
    } else { 
     document.getElementById("count").innerHTML = counter; 
     } 
}, 1000);​ 

更新: http://jsfiddle.net/6wxu3/1/

+0

谢谢@timtastic这正是我所期待的,它的工作ks太棒了! – Baig

+0

jsfiddle的URL是一个404 http://jsfiddle.net/6wxu3/1/ –

1

header("Refresh: 2; url=$your_url");

切记不要在标题前加上任何HTML内容。

+0

谁低估了这个答案应该给出一个理由。它正确回答了OP的问题。 – Jocelyn

+0

这是不正确的,问题是减少10,而不是重定向与PHP –

+1

该问题已修改此答案后发布。 [原始问题](http://stackoverflow.com/posts/12498209/revisions)不是很清楚,必须在屏幕上显示动态倒计时。 – Jocelyn

7

你不能用纯PHP做到这一点 - 但JavaScript是你的朋友在这里。

更改HTML投入的秒数在span

<b><span id="count">10</span> Seconds</b> 

然后删除您meta标签,并使用这个JavaScript:

var count = 10; 
function decrement() { 
    count--; 
    if(count == 0) { 
     window.location = 'login.php'; 
    } 
    else { 
     document.findElementById("count").innerHTML = "" + count; 
     setTimeout("decrement", 1000); 
    } 
} 
setTimeout("decrement", 1000); 

这将递减页每对数秒,然后重定向到login.php当计数器达到0.