如何在PHP中的特定时间刷新页面?

时间:2017-03-29 06:28:44

标签: php ajax

<?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>
<html>
    <head>
    <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>

//在这个代码中输入第二个我不会像12.00那样传递时间然后代码在10秒页面刷新后执行上面的代码并且每10秒产生一次数字并且我也不会在特定时间生成1个随机数< / p>

4 个答案:

答案 0 :(得分:1)

您可以使用此小Javascript代码段刷新页面。

window.onload = function() {
	setInterval(function() {
		location.reload(true);
	},21 * 1000); //21 is after how much seconds you wanna reload!
};

答案 1 :(得分:0)

你应该使你的代码像:

<?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
?>
<html>
    <head>
<script type="text/javascript">
    setInterval(function() {
        window.location.href = '<?php echo $page?>';
    },<?php echo (int)$sec ?> * 1000); 
</script>
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>

答案 2 :(得分:0)

PHP是服务器端,没有来自浏览器的请求就不会调用任何代码,解决方案是AJAX。在你的情况下尝试这样的事情(这个特定的例子你需要jQuery):

window.setInterval(function(){
  $.ajax({
    url:"my-file.php",
    success:function(data){
      //now data is the current time on the server, react accordingly with location.reload(true);
  });

}, 10000); // check every 10 seconds (change to any milliseconds you want)

在你的my-file.php中,只需回显服务器时间

答案 3 :(得分:0)

您可以在JavaScript和PHP中执行此操作,JavaScript解决方案已在上面。这是一个PHP解决方案:

<?php

$page = $_SERVER['PHP_SELF'];
$sec = "10";

date("Y-m-d");

date_default_timezone_set('Asia/Kolkata');
$time= date('H:i');

if($time == '11:51')
{
    echo mt_rand(0,9);
    echo '<br>';
}
?>
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");
?>
<html>
    <head>
    </head>
    <body>
    <?php
        echo "Watch the page reload itself in 10 second!";
    ?>
    </body>
</html>