JavaScript or JQuery 獲取服務器時間

用js作時間校訂,獲取本機時間,是存在bug的。html

使用js也可獲取到服務器時間,原理是使用 ajax請求,返回的頭部信息就含有服務器端的時間信息,獲取到就能夠了(有的IE下扔不會正常獲取,仍是更建議走後臺接口的方式吧)。如下:ajax

一、依賴jQuery服務器

代碼:異步

function getServerDate() {
    var serverDate;
    $.ajax({
        async: false,
        type: "POST",
        success: function (result, status, xhr) {
            serverDate= new Date(xhr.getResponseHeader("Date"));
        },
        error: function (result, status, xhr) {
            serverDate= new Date();
        },
    });
    return serverDate;
}

 

以上函數返回的就是一個Date對象,注意在使用ajax時必須同步,要否則沒法返回時間日期。async

無需填寫請求連接;函數

若是服務器時間和本地時間有時差,須要作校訂。spa

二、原生code

代碼:server

複製代碼
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()必須使用同步;htm

無需填寫請求連接;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: 未找到頁面

轉自:https://www.cnblogs.com/hellobook/p/6112182.html

相關文章
相關標籤/搜索