XMLHttpRequest: getAllResponseHeaders() 方法
注意:此功能在 Web Workers 中可用,但 Service Workers 除外。
XMLHttpRequest 方法 getAllResponseHeaders() 返回所有響應頭,以 CRLF 分隔,作為一個字串;如果沒有收到響應,則返回 null。
如果發生了網路錯誤,則返回一個空字串。
注意: 對於 multipart 請求,此方法返回的是請求的當前部分的頭資訊,而不是原始通道的頭資訊。
語法
js
getAllResponseHeaders()
引數
無。
返回值
一個字串,表示所有響應頭(除了欄位名為 Set-Cookie 的頭)以 CRLF 分隔;如果沒有收到響應,則返回 null。如果發生了網路錯誤,則返回一個空字串。
原始頭資訊字串示例
http
date: Fri, 08 Dec 2017 21:04:30 GMT\r\n
content-encoding: gzip\r\n
x-content-type-options: nosniff\r\n
server: meinheld/0.6.1\r\n
x-frame-options: DENY\r\n
content-type: text/html; charset=utf-8\r\n
connection: keep-alive\r\n
strict-transport-security: max-age=63072000\r\n
vary: Cookie, Accept-Encoding\r\n
content-length: 6502\r\n
x-xss-protection: 1; mode=block\r\n
每行都以回車符和換行符(\r\n)結束。它們實際上是分隔每個頭資訊的定界符。
注意: 在現代瀏覽器中,根據最新規範,頭資訊名稱將以全小寫形式返回。
示例
此示例檢查請求的 readystatechange 事件中的頭資訊。程式碼演示瞭如何獲取原始頭資訊字串,以及如何將其轉換為一個單獨的頭資訊陣列,然後如何使用該陣列建立頭資訊名稱到其值的對映。
js
const request = new XMLHttpRequest();
request.open("GET", "foo.txt", true);
request.send();
request.onreadystatechange = () => {
if (request.readyState === request.HEADERS_RECEIVED) {
// Get the raw header string
const headers = request.getAllResponseHeaders();
// Convert the header string into an array
// of individual headers
const arr = headers.trim().split(/[\r\n]+/);
// Create a map of header names to values
const headerMap = {};
arr.forEach((line) => {
const parts = line.split(": ");
const header = parts.shift();
const value = parts.join(": ");
headerMap[header] = value;
});
}
};
完成此操作後,您可以例如:
js
const contentType = headerMap["content-type"];
此程式碼將 Content-Type 頭資訊的值獲取到變數 contentType 中。
規範
| 規範 |
|---|
| XMLHttpRequest # getallresponseheaders()-方法 |
瀏覽器相容性
載入中…