数据请求更新时间:2025-12-17 15:55:04
XMLHttpRequest
基础信息说明
功能概述:创建并发送 HTTP(S) 请求,监听状态变化与结果
| 项目 | 说明 |
| 版本要求 | 无 |
| 前提条件 | 目标 URL 可访问、网络权限已配置 |
| 使用限制 | 无 |
| 相关教程 | 参考 MDN: XMLHttpRequest |
参数说明
xmlHttp = new XMLHttpRequest()
构造函数无参数,调用后同步返回网络请求对象。
返回值说明
new XMLHttpRequest() 为同步构造;调用 open/send 后的请求流程与事件为异步(默认)。
- 创建后返回
xmlHttp对象,常用属性与事件如下:
| 属性名 | 类型 | 说明 |
| xmlHttp.onreadystatechange | Function(Event event) | 当 readyState 属性发生变化时调用的事件处理函数 |
| xmlHttp.readyState | Number | 请求状态:0 UNSENT1 OPENED2 HEADERS_RECEIVED3 LOADING4 DONE |
| xmlHttp.response | any | 响应结果,类型由 responseType 决定(默认为字符串格式) |
| xmlHttp.responseText | String | 文本响应内容,仅在 responseType 为 空字符串或 text 时可用 |
| xmlHttp.responseType | String | 响应类型。可选值:空字符串、text、arraybuffer、blob、document、json |
| xmlHttp.responseURL | String | 最终响应 URL(包含重定向后的地址,只读) |
| xmlHttp.responseXML | Document | XML 响应文档;仅当响应为 XML 且 MIME 正确时可用,否则为 null |
| xmlHttp.status | Number | HTTP 状态码(如 200、404) |
| xmlHttp.statusText | String | HTTP 状态文本(如 OK、Not Found) |
| xmlHttp.timeout | Number | 设置超时时间(毫秒),仅异步请求生效,超时触发 ontimeout |
| xmlHttp.withCredentials | Boolean | 指定跨域请求是否携带证书(Cookie、HTTP 认证);需服务端允许 |
- 创建后返回 xmlHttp 对象,常用方法说明如下:
签名中"?"代表参数可以选择
| 方法名 | 签名 |
| xmlHttp.abort() | xmlHttp.abort(): void |
| xmlHttp.getAllResponseHeaders | xmlHttp.getAllResponseHeaders(): string |
| xmlHttp.getResponseHeader | xmlHttp.getResponseHeader(name: string): string | null |
| xmlHttp.open | xmlHttp.open(method: string, url: string, async?: boolean, user?: string, password?: string): void |
| xmlHttp.overrideMimeType | xmlHttp.overrideMimeType(mime: string): void |
| xmlHttp.send | xmlHttp.send(body?: Document | Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams | string | null): void |
| xmlHttp.setRequestHeader | xmlHttp.setRequestHeader(name: string, value: string): void |
回调结果说明
- 触发时机:
- readystatechange:每次 readyState 改变时触发(0→4 的各阶段)
- load:请求成功完成且 readyState = 4 时触发(含 2xx/3xx)
- error:网络错误或跨域被阻止时触发(常见 status = 0)
- timeout:达到 timeout 毫秒未完成时触发
- progress:下载过程触发进度事件(可读取 event.loaded/event.total)
- loadend:请求结束(成功、失败或中断)后触发
回调成功
load 成功形态
| 属性名 | 类型 | 说明 |
| event | Event | 事件对象,可通过 event.target === xmlHttp 获取实例;响应内容从 response/responseText 读取 |
回调失败
error/timeout/abort 失败形态
| 属性名 | 类型 | 说明 |
| event | Event | 事件对象;失败场景下 status 可能为 0,错误细节需结合网络与控制台日志排查 |
错误码
- 无固定错误码;通过 status 与事件判断:
- status = 200:成功
- status = 304:命中缓存
- status = 4xx/5xx:服务器返回错误
- status = 0:网络错误或跨域被阻止
示例代码
// GET JSON 示例
const xhr = new XMLHttpRequest()
xhr.responseType = 'json'
xhr.open('GET', 'https://api.example.com/data')
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
console.log('响应 JSON', xhr.response)
} else {
console.error('HTTP 错误', xhr.status, xhr.statusText)
}
}
xhr.onerror = function (e) {
console.error('网络错误', e)
}
xhr.send()上一篇:WebSocket
下一篇:下载
文档内容是否有帮助?
有帮助
无帮助