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 |
浏览器兼容性
加载中…