var req = new XMLHttpRequest(); req.open('GET', location, false); req.send(null); console.log(req.getResponseHeader('Date'));
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狀態來作不一樣的操做。ajax
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有四種狀態,方便作不一樣處理:服務器
失敗狀態,status的值:
200: "OK"
404: 未找到頁面異步