使倒数计时器抵制页面刷新

时间:2017-04-14 07:12:24

标签: javascript php mysql

好日子好人。我一直在使用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);
?>
如果有人帮我弄明白我哪里出错了,我会很高兴的

1 个答案:

答案 0 :(得分:0)

您需要进行测试以查看$_SESSION['start_time']是否已存在。如果是,请根据当前时间使用该值进行计算并继续倒计时。

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