基本思路是加载页面时首先与服务器进行时间同步,然后在这个时间的基础上每秒刷新页面显示时间
<!DOCTYPE html><html><head><meta charset="utf-8"><title>前端获取服务器时间并更新</title></head><body><p id="time"></p></body><script>var i = 0;var sysTime = null;//每秒更新页面显示时间var int = self.setInterval("handle()", 1000);function handle() {if (i == 0) {synchronization();} else {time();}i++;}//本地计算时间function time() {var curDate = new Date(sysTime);;curDate.setSeconds(curDate.getSeconds() + 1);sysTime = curDate;document.getElementById("time").innerHTML = "服务器时间:" + curDate.getFullYear() + "-" + (curDate.getMonth() + 1) + "-" + curDate.getDate() + " " + curDate.getHours() + ":" + curDate.getMinutes() + ":" + curDate.getSeconds();}//同步服务器时间function synchronization() {var xhr = new XMLHttpRequest();if (!xhr) {xhr = new ActiveXObject("Microsoft.XMLHTTP");}xhr.open("HEAD", location.href, true);xhr.onreadystatechange = function () {var time = null,curDate = null;if (xhr.readyState == 2) {// 获取响应头里的时间戳time = xhr.getResponseHeader("Date");curDate = new Date(time);sysTime = curDate;document.getElementById("time").innerHTML = "服务器时间:" + curDate.getFullYear() + "-" + (curDate.getMonth() + 1) + "-" + curDate.getDate() + " " + curDate.getHours() + ":" + curDate.getMinutes() + ":" + curDate.getSeconds();}}xhr.send(null);}</script></html>
