我正在网站上。我需要在页面上添加一个计时器,例如从DD :: hh:mm 02:12:34倒数到0。一旦计时器达到0,就必须向数据库发送查询以通知它计时器已结束。
我将如何设置此计时器?
此外,无论当前打开的会话如何,都必须发送计时器倒数结束时的查询。 (因此,对于0个活动会话,仍然需要处理该事件)
编辑:我没有机器来运行计时器程序
答案 0 :(得分:0)
最简单的方法是使用Ajax调用的php脚本。为initializeClock()
函数设置您要执行MySQL查询的死区时间。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
initializeClock('timerView', '2018-8-26 14:12:00');
});
</script>
<div id="messages"></div>
<div id="timerView"></div>
<div id="quiz_body"></div>
<script src="script.js"></script>
</body>
</html>
script.js
// This function just call the php script over Ajax to execute MySQL query...
var queryToDb = function () {
$.ajax({
url: '/mysql.php',
type: 'POST',
async: true,
data: {
done: true
},
success: function (response) {
$('#quiz_body').html(response);
startTimer();
},
error: function (xhr, type, exception) {
var _msg = "Service through error: (" + xhr.status + ") " + exception.toString();
var _err = $('#messages');
_err.text(_msg).show();
}
});
}
// return apropriate countdown information as hour, minutes, sec...
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
// initialize countdown...
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var timeinterval = setInterval(function () {
var t = getTimeRemaining(endtime);
clock.innerHTML = 'days: ' + t.days + '<br>' +
'hours: ' + t.hours + '<br>' +
'minutes: ' + t.minutes + '<br>' +
'seconds: ' + t.seconds;
if (t.total <= 0) {
clearInterval(timeinterval);
queryToDb();
}
}, 1000);
}
mysql.php
<?php
if($_POST){
// Create mysql conection and query here...
$db = new mysqli('localhost','user','password','dbname');
// Check for errors
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
// Do query if a connection has success...
$result = $db->query("INSERT INTO table (some_name) VALUES ('Some value');");
if($result){
$db->close();
die('OK');
}else{
die($someErrorMessage);
}
}
一种替代方法是调用API而不是调用Ajax。