🍶 JavaScript XMLHttpRequest
XMLHttpRequest 是一个内建的浏览器对象,它允许使用 JavaScript 发送 HTTP 请求。它可以操作任何数据,而不仅仅是 XML 格式。可以用它来上传 / 下载文件,跟踪进度等。
如今 JavaScript 中一般使用
fetch方法。
# 使用 XMLHttpRequest
一般使用它发送网络请求有两种执行模式:
- 同步;
- 异步;
异步发送网络请求的步骤:
创建
XMLHttpRequest:let xhr = new XMLHttpRequest();1XMLHttpRequest的构造器没有参数。初始化
xhr:xhr.open(method, URL, [async, user, password])1method:HTTP 方法;URL:请求 URL。通常是一个字符串或者是 URL 对象;async:如果显式地设置为false,那么请求将会以同步的方式处理;user/password:HTTP 基本身份验证(如果需要的话)的登录名和密码。
发送请求,
send方法会建立连接,并将请求发送到服务器。:xhr.send([body])1body:可选参数,包含了 request body。
监听
xhr事件以获取响应。常用的事件:load:当请求完成(即使 HTTP 状态为 400 或 500 等),并且响应已完全下载。error:当无法发出请求,例如网络中断或者无效的 URL。progress:在下载响应期间定期触发,报告已经下载了多少。
xhr.onload = function() { alert(`Loaded: ${xhr.status} ${xhr.response}`); }; xhr.onerror = function() { // 仅在根本无法发出请求时触发 alert(`Network Error`); }; xhr.onprogress = function(event) { // 定期触发 // event.loaded —— 已经下载了多少字节 // event.lengthComputable = true,当服务器发送了 Content-Length header 时 // event.total —— 总字节数(如果 lengthComputable 为 true) alert(`Received ${event.loaded} of ${event.total}`); };1
2
3
4
5
6
7
8
9
10
11
12
13
14
🌰 例子 / 一个完整的 xhr 发送请求实例:
let xhr = new XMLHttpRequest();
xhr.open('GET', '/article/xmlhttprequest/example/load');
xhr.send();
xhr.onload = function() {
if (xhr.status != 200) { // 分析响应的 HTTP 状态
alert(`Error ${xhr.status}: ${xhr.statusText}`); // 例如 404: Not Found
} else { // 显示结果
alert(`Done, got ${xhr.response.length} bytes`); // response 是服务器响应
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`); // 没有 Content-Length
}
};
xhr.onerror = function() {
alert("Request failed");
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
当服务器有了响应,则 xhr 属性中有:
status:HTTP 状态码(200,404,403等,如果出现非 HTTP 错误,则为0)statusText:HTTP 状态消息(字符串)(状态码为200对应于OK,404对应于Not Found,403对应于Forbidden。)response:服务器响应体。
对请求设置超时属性 timeout :
xhr.timeout = 10000; // timeout 单位是 ms,此处即 10 秒
1
如果在给定时间内请求没有成功执行,请求就会被取消,并且触发
timeout事件。
对请求 URL 设置参数:
let url = new URL('https://google.com/search');
url.searchParams.set('q', 'test me!');
// 参数 'q' 被编码
xhr.open('GET', url); // https://google.com/search?q=test+me%21
1
2
3
4
5
2
3
4
5
使用 URL 对象,并且
searchParams.set方法,确保参数的正确编码。
# 设置响应类型
可以使用 xhr.responseType 属性来设置响应格式:
""(默认)响应格式为字符串,"text"—— 响应格式为字符串,"arraybuffer"—— 响应格式为ArrayBuffer(对于二进制数据,请参见 ArrayBuffer,二进制数组 (opens new window)),"blob"—— 响应格式为Blob(对于二进制数据,请参见 Blob (opens new window)),"document"—— 响应格式为 XML document(可以使用 XPath 和其他 XML 方法)或 HTML document(基于接收数据的 MIME 类型)"json"—— 响应格式为 JSON(自动解析)。
编辑 (opens new window)
📢 上次更新: 2022/09/02, 10:18:16
