除了回應本文之外,HTTP 標頭其實還藏著不少有用資訊:檔案大小、伺服器類型、內容格式、最後修改時間等等。透過 getResponseHeader(),我們就能在不解析內容的情況下把這些中繼資料讀出來。
以下範例抓的是 ajax_info.txt 的 Last-Modified 標頭,也就是該檔最後一次被修改的時間。
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url) {
var xmlhttp;
if (window.XMLHttpRequest) { // IE7+、Firefox、Chrome、Opera、Safari
xmlhttp = new XMLHttpRequest();
} else { // IE6、IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('p1').innerHTML =
"Last modified: " + xmlhttp.getResponseHeader('Last-Modified');
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<p id="p1">The getResponseHeader() function is used to return specific header
information from a resource, like length, server-type, content-type, last-modified, etc.</p>
<button onclick="loadXMLDoc('ajax_info.txt')">Get "Last-Modified" information</button>
</body>
</html>
getResponseHeader(名稱) 的字串寫法不分大小寫,'Last-Modified' 與 'last-modified' 都能取得同一個值。若想一次拿到全部標頭,可以呼叫 getAllResponseHeaders(),它會回傳以 CRLF 分隔的完整字串。
要注意的是,標頭由伺服器決定要不要送出。如果目標資源是動態頁面、或伺服器(含 CDN、反向代理)刻意關閉了某個標頭,那麼讀到的會是 null,因此實務上建議先判空再使用,例如:
var lm = xmlhttp.getResponseHeader('Last-Modified');
document.getElementById('p1').innerHTML = lm ? "Last modified: " + lm : "此資源未提供 Last-Modified";
此外,跨來源請求時,自訂標頭需要伺服器在 Access-Control-Expose-Headers 中明確列出,否則瀏覽器不會讓 JavaScript 讀到,這一點在串接第三方 API 時特別容易踩到。