2017-04-14 55 views
1

美好的一天好人。我一直在使用php,mysql,javascript和ajax进行倒数计时。计时器正在工作,但当页面刷新后重新启动,我不知道我出错的地方。让倒数计时器抵挡页面刷新

我的定时器功能:

public function timer(){ 
    $this->getServer(); 
    $t = 45; 
    $duration = ""; 
    try{ 
     $connection = new PDO("mysql:host=$this->serverName;dbname=$this->serverDatabase",$this->serverUsername,$this->serverPassword); 
     $time = $connection->prepare("SELECT * FROM duration WHERE duration='$t'"); 
     $time->execute(); 

     if($time->rowCount()>=1){ 

      while($rows = $time->fetch(PDO::FETCH_ASSOC)){ 
      $duration = $rows["duration"]; 
      } 
     } 
    $_SESSION["duration"] = $duration; 
    $_SESSION["start_time"] = date("Y-m-d H:i:s"); 

    $end_time = date('Y-m-d H:i:s', strtotime('+'.$_SESSION["duration"].'minutes', strtotime($_SESSION["start_time"]))); 

    $_SESSION["end_time"] = $end_time; 
    } 
    catch(PDOException $e){ 

     die($e->getMessage()); 
    }  
} 

test.php 

session_start(); 
    require_once("connections.php"); 
    require_once("secure.php"); 

    $timer = new main(); 
    $timer->setServer($serverName,$serverDatabase,$serverUsername,$serverPassword); 
    $timer->getServer(); 
    $timer->timer(); 
?> 

<div id="response"></div> 

<script type="text/javascript"> 
    setInterval(function() 
    { 
     var xmlhttp = new XMLHttpRequest(); 
     xmlhttp.open("GET", "response.php", false); 
     xmlhttp.send(null); 
     document.getElementById("response").innerHTML=xmlhttp.responseText; 
    },1000); 
</script> 
response.php 

<?php 
session_start(); 

$from_time1=date("Y-m-d H:i:s"); 
$to_time1= $_SESSION["end_time"]; 

$timeFirst=strtotime($from_time1); 
$timeSecond=strtotime($to_time1); 

$differenceInSeconds = $timeSecond-$timeFirst; 

echo gmdate("H:i:s",$differenceInSeconds); 
?> 

,如果有人可以帮助我找出其中我得到错误

回答

0

您需要测试,看看是否$_SESSION['start_time']已经存在,我会很高兴。如果是,则使用该值根据当前时间计算并继续倒计时。

if(isset($_SESSION['start_time'])){ 
    //calculate time left 
} 
+0

其不工作 – healer

+0

你确定你没有重写你的session变量吗? – Difster

+0

是的,我很确定 – healer

相关问题