需獲取資源的最後修改時間、內容類型、長度等頭部信息,而不下載完整內容。可用 HEAD 請求或 GET 後讀取響應頭。
<!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 returns specific header information...</p>
<button onclick="loadXMLDoc('ajax_info.txt')">Get "Last-Modified" information</button>
</body>
</html>
xmlhttp.getResponseHeader('Header-Name'):獲取單個響應頭字段值。xmlhttp.getAllResponseHeaders():獲取所有頭部字符串(換行分隔)。| 字段 | 說明 |
|---|---|
| Last-Modified | 資源最後修改時間 |
| Content-Type | MIME 類型 |
| Content-Length | 響應體長度(字節) |
| ETag | 實體標籤,用於緩存驗證 |
| Server | 服務器軟件信息 |
跨域請求需服務器配置 Access-Control-Expose-Headers 才能讀取自定義頭部。