XMLHttpRequest: send() 方法
注意:此功能在 Web Workers 中可用,但 Service Workers 除外。
XMLHttpRequest 方法 send() 將請求傳送到伺服器。
如果請求是非同步的(這是預設設定),此方法將在傳送請求後立即返回,並透過事件交付結果。如果請求是同步的,此方法將一直阻塞直到響應到達。
send() 接受一個可選引數,允許您指定請求的主體;這主要用於 PUT 等請求。如果請求方法是 GET 或 HEAD,則 body 引數將被忽略,請求主體設定為 null。
如果未使用 setRequestHeader() 設定 Accept 標頭,則會發送一個型別為 "*/*"(任何型別)的 Accept 標頭。
語法
js
send()
send(body)
引數
body可選-
要傳送到 XHR 請求中的資料主體。這可以是
- 一個
Document,在這種情況下,它在傳送前會被序列化。 - 一個
XMLHttpRequestBodyInit,根據 Fetch 規範,它可以是Blob、ArrayBuffer、TypedArray、DataView、FormData、URLSearchParams或一個字串。 null
如果未指定 body 的值,則使用預設值
null。 - 一個
傳送二進位制內容(例如,在檔案上傳中)的最佳方法是結合使用 TypedArray、DataView 或 Blob 物件和 send() 方法。
返回值
無(undefined)。
異常
InvalidStateErrorDOMException-
如果
send()已經為請求呼叫過,和/或請求已完成,則會丟擲此異常。 NetworkErrorDOMException-
如果需要獲取的資源型別是 Blob,並且方法不是
GET,則會丟擲此異常。
示例:GET
js
const xhr = new XMLHttpRequest();
xhr.open("GET", "/server", true);
xhr.onload = () => {
// Request finished. Do processing here.
};
xhr.send(null);
// xhr.send('string');
// xhr.send(new Blob());
// xhr.send(new Int8Array());
// xhr.send(document);
示例:POST
js
const xhr = new XMLHttpRequest();
xhr.open("POST", "/server", true);
// Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = () => {
// Call a function when the state changes.
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// Request finished. Do processing here.
}
};
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
規範
| 規範 |
|---|
| XMLHttpRequest # the-send()-method |
瀏覽器相容性
載入中…