HTML5如何通过XMLHttpRequest获取数据_HTML5XHR取数方式【梳理】

XMLHttpRequest 在现代 HTML5 页面中仍可直接使用,但新项目不推荐手动封装;它作为底层 API 被 fetch 和 axios 封装,适用于老代码维护、精细控制请求(如进度监听)或 IE10+ 兼容场景。

XMLHttpRequest 能否在现代 HTML5 页面中直接使用

能,但不推荐新项目直接用 XMLHttpRequest 手动封装。它仍是浏览器原生支持的底层 API,fetch()axios 都构建在其之上。如果你维护老代码、需要精细控制请求生命周期(比如监听 upload.onprogress),或需兼容 IE10+,XMLHttpRequest 仍有明确价值。

最简可用的 XMLHttpRequest GET 请求写法

注意:必须调用 .open() 后再设置 .onload,否则可能错过状态变更;.send() 必须显式调用,即使无 body。

  • GET 请求无需设置 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();

POST 提交

JSON 数据时容易漏掉的关键点

常见错误是只传 JS 对象却没序列化,或忘了设请求头——这会导致后端收到空体或解析失败。

  • 必须用 JSON.stringify() 将数据转为字符串
  • 必须手动设置 Content-Type: application/json
  • .responseType = "json" 对 POST 同样有效,但仅影响响应解析
  • 如果后端返回非 2xx 状态码(如 400),.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 替代了大部分 XMLHttpRequest 使用场景

根本差异不在功能,而在默认行为和链式处理逻辑:fetch() 默认不带 cookie、不自动 reject 错误状态码(404/500 仍进 then)、返回 Promise 而非事件驱动。这些设计让代码更扁平,但也容易忽略错误分支。

  • XMLHttpRequest.abort() 是唯一可取消原生请求的方式;fetch() 需配合 AbortController
  • 上传进度只能用 XMLHttpRequest.upload.onprogressfetch 无等效机制
  • IE 完全不支持 fetch,若需兼容 IE11,XMLHttpRequest 是底线选择

真正该纠结的不是“用不用”,而是“在哪一层封装”。裸写 XMLHttpRequest 现在基本只出现在 polyfill、调试工具或极简环境里。