XMLHttpRequest 在现代 HTML5 页面中仍可直接使用,但新项目不推荐手动封装;它作为底层 API 被 fetch 和 axios 封装,适用于老代码维护、精细控制请求(如进度监听)或 IE10+ 兼容场景。
能,但不推荐新项目直接用 XMLHttpRequest 手动封装。它仍是浏览器原生支持的底层 API,fetch() 和 axios 都构建在其之上。如果你维护老代码、需要精细控制请求生命周期(比如监听 upload.onprogress),或需兼容 IE10+,XMLHttpRequest 仍有明确价值。
注意:必须调用 .open() 后再设置 .onload,否则可能错过状态

.send() 必须显式调用,即使无 body。
Content-Type
.responseType 默认是 ""(即字符串),设为 "json" 可让 .response 自动解析(但仅限 200 状态且响应体合法)xhr.status === 200,不能只依赖 xhr.readyState === 4
const xhr = new XMLHttpRequest();
xhr.open("GET", "/api/users");
xhr.responseType = "json";
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.response); // 已解析为对象
} else {
console.error("请求失败:", xhr.status, xhr.statusText);
}
};
xhr.onerror = function() {
console.error("网络错误");
};
xhr.send();
常见错误是只传 JS 对象却没序列化,或忘了设请求头——这会导致后端收到空体或解析失败。
JSON.stringify() 将数据转为字符串Content-Type: application/json
.responseType = "json" 对 POST 同样有效,但仅影响响应解析.onload 仍会触发,需主动判断 status
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/login");
xhr.responseType = "json";
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
console.log("登录成功", xhr.response);
} else {
console.warn("登录失败", xhr.status, xhr.response?.message);
}
};
xhr.send(JSON.stringify({ username: "admin", password: "123" }));
根本差异不在功能,而在默认行为和链式处理逻辑:fetch() 默认不带 cookie、不自动 reject 错误状态码(404/500 仍进 then)、返回 Promise 而非事件驱动。这些设计让代码更扁平,但也容易忽略错误分支。
XMLHttpRequest 的 .abort() 是唯一可取消原生请求的方式;fetch() 需配合 AbortController
XMLHttpRequest.upload.onprogress,fetch 无等效机制fetch,若需兼容 IE11,XMLHttpRequest 是底线选择真正该纠结的不是“用不用”,而是“在哪一层封装”。裸写 XMLHttpRequest 现在基本只出现在 polyfill、调试工具或极简环境里。