HTTP 響應頭裡藏著不少有用信息:文件大小、服務器類型、內容類型、最後修改時間等。Ajax 請求完成後,可以用 getResponseHeader() 把指定字段取出來。
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
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(name) 按名稱讀取響應頭,名稱不區分大小寫,字段不存在時返回 null(而非空字符串),取值後建議做一次判空。
getAllResponseHeaders() 則一次性返回所有響應頭的原始文本,格式為每行一組「名稱: 值」,需要自行拆分解析。
必須在 readyState 為 4 之後調用。 請求未完成時響應頭尚未到齊,此時讀取會拋出錯誤。
這是使用中最容易踩的坑:跨域請求時,瀏覽器默認只暴露六個「安全」響應頭——Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。其他自定義頭(如 Authorization、X-Token、X-Total-Count)即使服務端返回了,JS 也讀不到。
要讀取自定義頭,必須由服務端在 CORS 響應中顯式聲明:
Access-Control-Allow-Origin: * Access-Control-Expose-Headers: X-Total-Count, X-Request-Id
這一點在分頁場景中尤其常見:後端把總數放在 X-Total-Count 頭裡返回,前端卻一直拿到 null,原因往往就是缺少 Expose-Headers 配置。
fetch('ajax_info.txt')
.then(function (response) {
console.log('Last-Modified:', response.headers.get('Last-Modified'));
console.log('全部響應頭:');
response.headers.forEach(function (v, k) { console.log(k + ': ' + v); });
return response.text();
})
.then(function (body) { console.log(body); });
Response.headers 是一個 Headers 對象,支持 get()、has()、forEach() 等操作,比手寫字符串解析方便得多。要注意的是它同樣受上述 CORS 暴露規則約束。