XMLHttpRequest(简称 XHR)是浏览器最早提供的 AJAX 接口。虽然新项目更常用 fetch,但阅读旧代码、实现上传进度时仍会遇到它。
本节要点
- xhr.open() 配置请求方法和地址,xhr.send() 真正发出请求。
- readyState 表示请求阶段,等于 4 时响应才完整。
- status 是 HTTP 状态码,2xx 表示成功。
- responseType 可以设为 json,让浏览器自动解析 JSON。
可运行示例
页面会请求同一份 JSON,并实时打印请求阶段与结果。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>XMLHttpRequest 示例</title>
</head>
<body>
<h1>XMLHttpRequest</h1>
<button id="send">发送请求</button>
<pre id="log"></pre>
<script>
const log = document.getElementById('log');
document.getElementById('send').addEventListener('click', () => {
const xhr = new XMLHttpRequest();
xhr.open('GET', '/ajax/demo/data.json');
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
log.textContent += `readyState=${xhr.readyState}, status=${xhr.status}\n`;
if (xhr.readyState !== 4) return;
if (xhr.status >= 200 && xhr.status < 300) {
log.textContent += '成功,共 ' + xhr.response.length + ' 条数据\n';
log.textContent += JSON.stringify(xhr.response[0], null, 2);
} else {
log.textContent += '请求失败\n';
}
};
xhr.onerror = () => { log.textContent += '网络错误\n'; };
xhr.send();
});
</script>
</body>
</html>运行说明:点击按钮后观察日志。readyState 会依次经过 1、2、3、4,最终输出第一条数据。 在线运行示例 →
readyState 的含义
| 值 | 状态 | 说明 |
|---|---|---|
| 0 | UNSENT | 请求尚未建立。 |
| 1 | OPENED | 已调用 open()。 |
| 2 | HEADERS_RECEIVED | 已收到响应头。 |
| 3 | LOADING | 正在下载响应体。 |
| 4 | DONE | 请求完成,可以读取响应。 |
常见状态码
200 表示成功,201 表示已创建,301/302 表示重定向,400 表示请求有误,401 未登录,403 无权限,404 资源不存在,500 服务端错误。判断成功时应使用 status 区间,而不是只判断 200。
提示:XHR 的 onerror 只处理网络层错误,HTTP 4xx/5xx 仍会进入 onreadystatechange,需要自己判断 status。