1. 程式人生 > >js向伺服器傳送請求,獲取伺服器時間

js向伺服器傳送請求,獲取伺服器時間

1.開啟開發者工具中的console


2.複製下面程式碼

ajax()
  function ajax(option){
    var xhr = null;
    if(window.XMLHttpRequest){
      xhr = new window.XMLHttpRequest();
    }else{ // ie
      xhr = new ActiveObject("Microsoft")
    }
    // 通過get的方式請求當前檔案
    xhr.open("get","/");
    xhr.send(null);
    // 監聽請求狀態變化
    xhr.onreadystatechange = function
(){ var time = null, curDate = null; if(xhr.readyState===2){ // 獲取響應頭裡的時間戳 time = xhr.getResponseHeader("Date"); console.log(xhr.getAllResponseHeaders()) curDate = new Date(time); document.getElementById("time").innerHTML = "伺服器時間是:"+curDate.getFullYear()+"-"+(curDate.getMonth()+1)+"-"+curDate.getDate()+" "+curDate.getHours()+":"+curDate.getMinutes()+":"+curDate.getSeconds(); } } }

3.完成程式碼後回車,等待伺服器返回時間