前端獲取服務(wù)器時(shí)間

/** 
* @description 獲取服務(wù)器時(shí)間(無(wú)需后臺(tái)接口支持)
* @author jamieyan@tencent.com
* @param {Function} callback 成功回調(diào)
* @param {Function} error    失敗回調(diào)
*/
function getServerTime(callback, error){
    var xhr, dateStr;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    } else if(window.ActiveXObject){
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.onreadystatechange = function(){
        // 一般ajax取readyState為4時(shí)處理,
        // 因?yàn)檫@里只需要response header,所以可以早一些就得到結(jié)果
        if(xhr.readyState === 3){
            // 從response header里取得Date字段,不區(qū)分大小寫(xiě)
            // 所有標(biāo)準(zhǔn)的HTTP服務(wù)都會(huì)返回Date
            // 這里的Date便是服務(wù)器時(shí)間了
            dateStr = xhr.getResponseHeader("Date");
            // 處理回調(diào)
            if (dateStr && ("function" === typeof callback)) {
                callback(dateStr);
            } else if ("function" === typeof error){
                error(xhr);
            }
            // 時(shí)間都已經(jīng)取到了,可以把a(bǔ)jax停掉
            xhr.abort();
        }
    };
    // 這里的路徑要根據(jù)你的實(shí)際情況選擇
    // 因?yàn)橛行┓?wù)器404返回會(huì)比較慢
    // 盡量選擇返回body較小,反應(yīng)速度快的路徑
    xhr.open("GET", "/404.htm", true);
    xhr.send(null);
}


// 測(cè)試
getServerTime(function(dateStr){
    alert(dateStr);
}, function(){
    alert("error");
});

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容