2016-02-24 91 views
0

正如標題所說,我想要得到的響應頭日期的價值,但我不斷收到以下警告:獲取日期標題Asyncronously

在主線程同步的XMLHttpRequest已被棄用,因爲 其不利影響以最終用戶的體驗。如需更多幫助,請撥打 查詢https://xhr.spec.whatwg.org/

我的代碼:

function getxmlhttp() { 
    // although IE supports the XMLHttpRequest object, but it does not work on local files. 
    var forceActiveX = (window.ActiveXObject && location.protocol === "file:"); 
    if (window.XMLHttpRequest && !forceActiveX) { 
     return new XMLHttpRequest(); 
    }else { 
     try { 
      return new ActiveXObject("Microsoft.XMLHTTP"); 
     } catch(e) {} 
    } 
    alert ("Your browser doesn't support XML handling!"); 
    return null; 
}; 

function srvTime(){ 
    xmlHttp = getxmlhttp(); 
    //xmlHttp.open('HEAD',window.location.href.toString(),false); 
    //need to send this to a non-volitile page 
    xmlHttp.open('GET',"blank.php",false); 
    xmlHttp.setRequestHeader("Content-Type", "text/html"); 
    xmlHttp.send(null); 
    console.log("raw " + xmlHttp.getResponseHeader("Date")); 
    return xmlHttp.getResponseHeader("Date"); 
}; 

當我轉這行:

xmlHttp.open('GET',"blank.php",true); 

是真實的,值返回NULL

所以可以這樣做,還是我必須在控制檯中生存警告?

謝謝

+0

是jQuery的選項嗎?如果是,那麼看到這個答案。 http://stackoverflow.com/a/1457708/1437261 – Gogol

+0

你是否將腳本標記中包含的腳本從blank.php返回給客戶端? – dreamweiver

+1

您需要使用帶有異步請求的onreadystatechange/load處理程序,然後才能使用數據/頭文件。見https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Get_last_modified_date –

回答

0

作爲您的標題狀態,您必須異步地發出請求。這意味着您必須發出請求並等待它完成以獲取信息。像這樣的東西應該工作:

function srvTime(callback) { 
    xmlHttp = getxmlhttp(); 
    //xmlHttp.open('HEAD',window.location.href.toString(),false); 
    //need to send this to a non-volitile page 
    xmlHttp.onreadystatechange = function() { 
     if (xmlHttp.readyState == 4) { // The operation is complete 
      console.log("raw " + xmlHttp.getResponseHeader("Date")); 
      callback(xmlHttp.getResponseHeader("Date")); 
      xmlHttp = null; 
     } 
    }; 
    xmlHttp.open('GET', "blank.php", true); 
    xmlHttp.setRequestHeader("Content-Type", "text/html"); 
    xmlHttp.send(null); 
}; 

請注意,你必須改變你srvTime方法的簽名。你不能從它返回數據,調用者必須提供一個回調函數,一旦請求完成就會收到日期。

的你將如何使用該功能的新簽名的例子如下:

srvTime(function (serverDate) { 
    document.getElementById("clock").innerHTML = "Game Time: " + serverDate; 
}); 
+0

他只想要一個標題,所以HEAD可能是一個更好的動詞。 –

+0

@AlexK。是的,這是真的。爲了澄清,我的意圖是修改他現有的代碼就夠了。不過,現在你提到它了,你應該能夠在'readyState == 2'(頭部收到)處獲得頭部,這將是另一個優化。 –

+0

@JackA。好,所以我不明白的是「回調」。你能否解釋或指導我解釋如何從那裏獲取信息的地方?感謝您的幫助! – KeeganS