gpt4 book ai didi

javascript - 使倒数计时器抵抗页面刷新

转载 作者:行者123 更新时间:2023-11-30 22:00:54 25 4
gpt4 key购买 nike

美好的一天好人。我一直在使用 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);
?>

如果有人能帮我找出我哪里错了,我会很高兴

最佳答案

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

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

关于javascript - 使倒数计时器抵抗页面刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43406926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com