用js做時間校正,獲取本機時間,是存在bug的。
使用js也可獲取到服務器時間,原理是使用 ajax請求,返回的頭部信息就含有服務器端的時間信息,獲取到就可以了。以下:
1、依賴jQuery
代碼:
function getServerDate(){
return new Date($.ajax({async: false}).getResponseHeader("Date"));
}
以上函數返回的就是一個Date對象,注意在使用ajax時必須同步,要不然無法返回時間日期。
無需填寫請求鏈接;
如果服務器時間和本地時間有時差,需要做校正。
2、原生
代碼:
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()必須使用同步;
無需填寫請求鏈接;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有四種狀態,方便做不同處理:
- 0: 請求未初始化
- 1: 服務器連接已建立
- 2: 請求已接收
- 3: 請求處理中
- 4: 請求已完成,且響應已就緒
失敗狀態,status的值:
200: "OK"
404: 未找到頁面
轉自:http://www.cnblogs.com/hellobook/p/6112182.html
另外,如果服務器時間較對可以用:http://bjtime.cn/nt.asp
