JavaScript or JQuery 獲取服務器時間


用js做時間校正,獲取本機時間,是存在bug的。

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

1、依賴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時必須同步,要不然無法返回時間日期。

無需填寫請求鏈接;

如果服務器時間和本地時間有時差,需要做校正。

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: 未找到頁面

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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM