gpt4 book ai didi

javascript - 如何使用 php 中的按钮操作倒计时器?

转载 作者:行者123 更新时间:2023-11-29 18:32:02 25 4
gpt4 key购买 nike

我正在开发一个投标系统。我有一个计时器,可以从数据库中读取数据,并在到达 00:00 时显示一条消息。现在我想以这样的方式操纵计时器,当它 <= 10secs(00:00:00:10) 时,单击一个按钮,那么它应该重置回 00:00:00:10 并继续。定时器显示以日、小时、分钟和秒为单位。这是 JavaScript 代码

function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "<b>" + s + "</b>";
}

function CountBack(secs) {
if (secs < 0) {
document.getElementById("cntdwn").innerHTML = FinishMessage;
return;
}
DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));

document.getElementById("cntdwn").innerHTML = DisplayStr;
if (CountActive)
setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}

function putspan(backcolor, forecolor) {
document.write("<span id='cntdwn' style='background-color:" + backcolor +
"; color:" + forecolor + "'></span>");
}

if (typeof(BackColor)=="undefined")
BackColor = "white";
if (typeof(ForeColor)=="undefined")
ForeColor= "black";
if (typeof(TargetDate)=="undefined")
TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined")
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof(CountActive)=="undefined")
CountActive = true;
if (typeof(FinishMessage)=="undefined")
FinishMessage = "";
if (typeof(CountStepper)!="number")
CountStepper = -1;
if (typeof(LeadingZero)=="undefined")
LeadingZero = true;


CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dnow = new Date();
if(CountStepper>0)
ddiff = new Date(dnow-dthen);
else
ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(gsecs);

这是PHP代码

<body>
<?php
$mysqli = new mysqli("localhost","root","", "auction");
if (!$mysqli)
{
die('Could not connect: ' . mysql_error());
}

else{

$sql = "INSERT INTO bids (id, description, closing_date) VALUES
(NULL, 'Acer Aspire 4736', '2011-10-22 18:50:26')";

}


$result = $mysqli->query("SELECT * FROM bids WHERE id = 1");

$row = mysqli_num_rows($result);

if ($row == 0)
{
die('No record found.');
}

$row = $result->fetch_array();
echo "Description: " . $row[1] . "<br />";
$closedate = date_format(date_create($row[2]), 'm/d/Y H:i:s');
echo "Closing Date: " . $closedate;
?>
<p>Time Left:
</p>
<script language="JavaScript">
TargetDate = "<?php echo $closedate ?>";
BackColor = "blue";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "Bidding closed!";
</script>
<script language="JavaScript" src="countdown.js"></script>
</body>

这里是html中显示的代码

<?php
$A=0;
if ($A%4 ==0):;?>
<?php
while ($auction=$result->fetch_assoc()):;?>
<div class = "grid ">
<h4 class="c-head"><?=$auction['item_name']?></h4>
<img src='<?=$auction['item_image']?>' class="img-responsive">
<span class="timer">
<script language="JavaScript">
TargetDate = "<?php echo $closedate ?>";
BackColor = "";
ForeColor = "";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%%, %%H%%:%%M%%:%%S%%";
FinishMessage = "Bidding closed!";
</script>
<script language="JavaScript" src="countdown\countdown.js">
</script>

</span>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="digit" class="form-control"
name="duration">
<span class="input-group-btn "><button class="btn btn-
primary c-button" type="button" name="bid">Bid now!</button></span>
</div>

</div>

<?php endwhile; $A++; endif;?>

我是 php 新手...几周前才开始学习。非常感谢您的宝贵时间。

最佳答案

我写这个是为了帮助你开始。我目前没有开发环境,所以我没有运行这段代码。所有php文件必须放在同一目录下才能通信

需要时该文件应允许您与数据库进行通信。此外,我使用 PDO,这是在请求数据库以避免 SQL 注入(inject)时的良好实践。

请查看php文档http://php.net/manual/fr/class.pdo.php

// database_connection.php
$host = 'localhost';
$user = 'root'; // Bad idea to user root user ^^'
$password = 'yourpassword';
$dbname = 'auction';

try {
$dsn = sprintf('mysql:host=%s;dbname=%s', $host, $dbname);
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; // I active errors, if you are a beginner that'll help you, comment this in prod env
// I use PDO to avoid SQL injections, this line open a mysql connection, check the documentation
$connection = new PDO($dsn, $user, $password, $pdo_options);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
exit;
}

您必须实现一个带有描述输入的 HTML POST 表单,该表单将提交到此 PHP 文件

此文件处理出价的创建

// addBid.php
// You have to implement a HTLM POST form with the needed fields which will submit to this PHP file
// The url yourdomain.fr/addBid.php
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
if(!is_int($statusCode)) {
// The error code isnt an integer
throw new \Exception('error code isn\'nt an integer!');
}

if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
throw new \Exception('invalid error code !');
}

header('Location: ' . $url, true, $statusCode);
exit;
}

$description = isset($_POST['description']) ? $_POST['description'] : null;
$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended description isn't valid
if(empty($description) || !is_string($description)) {
redirectTo($urlListing);
}

// You should do some verification on the string that send the user, it can be malicious html/javascript code, XSS attack

// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'INSERT INTO bids(description, closing_date) VALUES(":description", ":closing_date")';
$statement = $connection->prepare($sql);
$success = $statement->execute([
':closing_date' => $stringDate,
':description' => $description
]);
if(!$success) {
echo 'The sql query didnt work as excepted';
exit;
}

$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the bid is created
$urlListing .= '?created=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page

这第三个文件处理数据库中的出价更新

// updateBid.php
// The url yourdomain.fr/updateBid.php?bidId=6 will update the bid with id 6 into database
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
if(!is_int($statusCode)) {
// The error code isnt an integer
throw new \Exception('error code isn\'nt an integer!');
}

if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
throw new \Exception('invalid error code !');
}

header('Location: ' . $url, true, $statusCode);
exit;
}

$bidId = isset($_GET['bidId']) ? $_GET['bidId'] : null;

$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended bidId isn't valid
if(empty($bidId) || !is_numeric($bidId)) {
redirectTo($urlListing);
}

// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'UPDATE bids SET closing_date = ":dateToModify" WHERE id = :id';
$statement = $connection->prepare($sql);
$success = $statement->execute([
':closing_date' => $stringDate,
':id' => $bidId
]);
if(!$success) {
echo 'The sql query didnt work as excepted';
exit;
}

$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the $bidId is present in database
$urlListing .= '?updated=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page

你应该做一些学习 PHP 和 MYSQL 的教程,这会对你有很大帮助:)此外,当您使用 PHP 框架时,一开始会比较困难,但之后您会通过阅读代码学到很多东西。并且该框架可以帮助您保持“良好实践”,在 php 中很容易做一些狗屎代码。我希望我没有那么多语法或逻辑错误,但我知道 stackoverflow 社区会在需要时纠正我对不起我的英语不好 !!如果您投赞成票,我们将不胜感激:)

关于javascript - 如何使用 php 中的按钮操作倒计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45595297/

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