用js作時間校訂,獲取本機時間,是存在bug的。ajax
使用js也可獲取到服務器時間,原理是使用 ajax請求,返回的頭部信息就含有服務器端的時間信息,獲取到就能夠了。如下:服務器
一、依賴jQuery異步
代碼:async
function getServerDate(){ return new Date($.ajax({async: false}).getResponseHeader("Date")); }
以上函數返回的就是一個Date對象,注意在使用ajax時必須同步,要否則沒法返回時間日期。函數
無需填寫請求連接;spa
若是服務器時間和本地時間有時差,須要作校訂。code
二、原生對象
代碼:blog
function getServerDate(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new window.XMLHttpRequest(); }else{ // ie xhr = new ActiveObject("Microsoft") } xhr.open("GET","/",false)//false不可變 xhr.send(null); var date = xhr.getResponseHeader("Date"); return new Date(date); }
一樣返回的是一個Date對象,xhr.open()必須使用同步;get
無需填寫請求連接;open,send,和getResponseHeader 必須按序編寫。
如需使用異步請求,可監聽onreadystatechange狀態來作不一樣的操做。
代碼以下:
function getServerDate(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new window.XMLHttpRequest(); }else{ // ie xhr = new ActiveObject("Microsoft") } xhr.open("GET","/",true); xhr.send(null); xhr.onreadystatechange=function(){ var time,date; if(xhr.readyState == 2){ time = xhr.getResponseHeader("Date"); date = new Date(time); console.log(date); } } }
使用異步不是很方便返回時間。
這裏的readyState有四種狀態,方便作不一樣處理:
失敗狀態,status的值:
200: "OK"
404: 未找到頁面