我正在实现一个ajax时钟,它应该在我的服务器上获取时间。我有美国/太平洋时间。但是我的时钟不会抓取服务器的时间,似乎显示了一个随机的时间。我不知道为什么。
这是我在客户端的脚本:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var start_time;
var current_time;
//gets current server time
var get_time = function () {
$.ajax({
type: 'GET',
url: '../Server_Side/clock.php',
data: ({ action : 'get_time' }),
success: (function (data) {
start_time = new Date(
data.year,
data.month,
data.day,
data.hour,
data.minute,
data.second
//comment
);
$('#clock').html(current_time.toLocaleTimeString("en-US", {timeZone:'America/Vancouver'}));
}),
dataType: 'json'
});
}
//counts 0.25s
var cnt_time = function () {
current_time = new Date(start_time.getTime() + 250);
$('#clock').html(current_time.toLocaleTimeString("en-US", {timeZone:'America/Vancouver'}));
start_time = current_time;
}
setInterval(cnt_time, 250); //add 250ms to current time every 250ms
setInterval(get_time, 30250); //sync with server every 30,25 second
get_time();
</script>这是我为服务器端准备的时钟:
<?php
if ( isset($_GET['action']) && !empty($_GET['action']) && $_GET['action'] == 'get_time' ) {
header('Content-type: application/json');
echo json_encode (
array (
'year' => date('Y'),
'month' => date('m'),
'day' => date('d'),
'hour' => date('h'),
'minute' => date('i'),
'second' => date('s')
)
);
}
else {
header('HTTP/1.1 404 Not Found');
echo '<h1>404 Not Found</h1>';
echo '<p>The page that you have requested could not be found.</p>';
}
?>发布于 2018-11-26 16:14:54
date('m')将在12之前返回01。您可能需要date('n') - 1,它返回0到11。对于JS Date对象,第二个参数接受monthIndex,它只接受0 (Jan)到11 (Dec)。
参考文献:
date JS Date:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
https://stackoverflow.com/questions/53476918
复制相似问题