Fetch API语法更简洁,基于promise,易于读写;2. XHR使用事件回调,代码复杂但控制精细;3. Fetch需手动处理http错误,XHR通过状态码判断;4. Fetch原生支持AbortController、流响应等现代特性;5. XHR兼容老旧浏览器,Fetch需polyfill;6. 现代项目推荐Fetch,旧系统或精细控制场景可用XHR。

在现代前端开发中,发送网络请求是与服务器交互的核心操作。javaScript 提供了多种方式实现这一功能,其中最常用的是 Fetch API 和传统的 XMLHttpRequest(XHR)。虽然两者都能完成请求任务,但在语法、可读性、功能和兼容性上存在明显差异。下面从多个维度进行对比,帮助你理解何时使用哪种方式。
语法简洁性与可读性
Fetch API 采用现代 javascript 的 Promise 语法,代码更简洁、逻辑更清晰。
Fetch 示例:
fetch('/api/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
而 XMLHttpRequest 使用事件驱动模型,嵌套回调多,代码结构较复杂。
XHR 示例:
const xhr = new XMLHttpRequest(); xhr.open('GET', '/api/data', true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log(json.parse(xhr.responseText)); } }; xhr.onerror = function () { console.error('Request failed'); }; xhr.send();
显然,Fetch 写法更符合现代开发习惯,易于理解和维护。
立即学习“Java免费学习笔记(深入)”;
错误处理机制
Fetch API 的错误处理容易被误解:只有网络错误会触发 catch,HTTP 状态码如 404 或 500 不会自动抛错,需要手动判断 response.ok。
fetch('/api/data') .then(response => { if (!response.ok) throw new Error(response.status); return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
XMLHttpRequest 则通过检查 status 和 readyState 来判断请求结果,虽然繁琐但控制更直接。
对现代特性的支持
Fetch 原生支持 JSON、流式响应、AbortController(用于取消请求)等现代特性。
- 使用 AbortController 可轻松中断请求:
const controller = new AbortController(); fetch('/api/data', { signal: controller.signal }) .then(response => response.json()) .then(data => console.log(data)); // 取消请求 controller.abort();
- 支持 Headers、Request、Response 等类,便于封装和测试。
- 与 async/await 结合更自然:
async function getData() { try { const response = await fetch('/api/data'); if (!response.ok) throw new Error(response.status); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } }
相比之下,XMLHttpRequest 对这些新特性的支持较弱,需额外封装才能实现类似功能。
浏览器兼容性与使用场景
Fetch 是较新的 API,IE 全系不支持,老版本 safari 和 edge 也有局限。如果需要支持老旧浏览器,XMLHttpRequest 仍是稳妥选择。
目前主流项目多基于现代浏览器或使用 Babel/webpack 构建,因此 Fetch 配合 polyfill 完全可行。
在以下情况推荐使用 Fetch:
而 XHR 更适合:
- 维护旧系统
- 需要精细控制请求过程(如上传进度分段处理)
- 环境无法引入 polyfill
基本上就这些。Fetch API 在设计上更先进,已成为主流选择;XMLHttpRequest 虽显陈旧,但依然可靠。根据项目需求和技术栈合理选择即可。


