# XMLHttpRequest

**XMLHttpRequest**（XHR）是浏览器中的一种 [JavaScript](https://www.edgepedia.org/zh/javascript) API，定义于 WHATWG 的一份活标准中，允许脚本在不重新加载页面的情况下通过 HTTP 在客户端与服务器之间传输数据。尽管名字如此，它其实可以获取任何类型的数据，而不只是 XML；这个名字是历史遗留的，与它的功能无关。<sup>[1](https://xhr.spec.whatwg.org/)</sup><sup> • </sup><sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)</sup>

| 关键事实 | 详情 |
|---|---|
| 是什么 | 一种为脚本提供客户端功能的 API，用于在客户端与服务器之间传输数据；名称是历史遗留的。<sup>[1](https://xhr.spec.whatwg.org/)</sup> |
| 起源 | 在微软 Exchange 2000 团队中创建，最初名为 XMLHTTP，随 Outlook Web Access for IE5（2000 年）一同发布；经由 Google Suggest 为公众所知。<sup>[3](https://www.alexhopmann.com/page/the-story-of-xmlhttp)</sup> |
| 标准历程 | 最初属于 WHATWG 的 HTML 工作，2006 年移至 W3C，2011 年底 Level 2 扩展被合并回来，2012 年底回归 WHATWG。<sup>[1](https://xhr.spec.whatwg.org/)</sup> |
| 请求状态 | `readyState` 从 `UNSENT`（0）依次经过 `OPENED`（1）、`HEADERS_RECEIVED`（2）、`LOADING`（3），到 `DONE`（4）。<sup>[1](https://xhr.spec.whatwg.org/)</sup> |
| 跨域 | XHR 遵循同源策略；跨站请求只有在服务器返回正确的 CORS 响应头时才有效，否则会抛出 `INVALID_ACCESS_ERR` 异常。<sup>[4](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS)</sup><sup> • </sup><sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)</sup> |
| 同步使用 | 主线程上的同步 XHR 已被废弃，正在从 Web 平台中移除；2022 年它仍被用于 2.5% 的移动端页面和 2.8% 的桌面端页面。<sup>[1](https://xhr.spec.whatwg.org/)</sup><sup> • </sup><sup>[6](https://cdn.httparchive.org/v1/static/almanac/ebooks/web_almanac_2022_en.pdf)</sup> |
| 可用性 | 自 2015 年 7 月起在各浏览器中广泛可用；可在 Web Worker 中使用，但 Service Worker 除外。<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)</sup> |

## 历史

XMLHTTP 诞生于微软的 Exchange 2000 团队。亚历克斯·霍普曼（Alex Hopmann）是微软的一位开发者，曾从事 Outlook 的互联网标准工作，后来领导微软 WebDAV 服务器的开发。他回忆说，Gmail 的客户端架构大致沿用了 Exchange 2000 中 Outlook Web Access for IE5 的设计，后者于 2000 年发布。大众注意到这项技术，是因为谷歌在 Google Suggest 功能中使用了它，有人查看了那个页面的源代码；而谷歌其实更早就在 Gmail 中使用了它，只是 Gmail 的 JavaScript 足够复杂，这项技术在那里没有引起注意。<sup>[3](https://www.alexhopmann.com/page/the-story-of-xmlhttp)</sup>

这项技术在 2005 年 2 月获得了它的文化名称：杰西·詹姆斯·加勒特（Jesse James Garrett）的文章《Ajax：Web 应用的新方法》为 XHR 驱动的 Web 应用创造了 [Ajax](https://www.edgepedia.org/zh/ajax-programming)（Asynchronous JavaScript and XML，异步 JavaScript 和 XML）一词，并以 Gmail、Google Suggest、Google Maps 和 Flickr 为例。<sup>[7](https://github.com/whatwg/web-history)</sup> 2005 年发布的 Opera 8 是 Opera 首个（有限）支持 XHR 的正式版本，这使得 XHR 在所有主流浏览器引擎中都可用了。<sup>[7](https://github.com/whatwg/web-history)</sup>

## 请求的工作方式

一个基本请求分三步：创建一个 `XMLHttpRequest` 对象，用方法和 URL 调用 `open()`，再调用 `send()`。事务完成后，对象中包含响应体和结果的 HTTP 状态。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)</sup> `open()` 方法的可选第三个参数 `async` 决定请求是异步处理（true，或省略）还是同步处理（false）。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)</sup>

对象通过 `readyState` 属性报告进度，其取值包括 `UNSENT`（0，对象已构造）、`OPENED`（1，`open()` 已成功调用）、`HEADERS_RECEIVED`（2，所有重定向已跟随、所有响应头已收到）、`LOADING`（3，正在接收响应体）和 `DONE`（4，传输完成或失败）。<sup>[1](https://xhr.spec.whatwg.org/)</sup> 响应数据通过若干属性暴露：`responseText` 以字符串返回响应体，`responseXML` 为 XML 或 HTML 响应返回解析后的 `Document`，`response` 则根据 `responseType` 的设置返回 `ArrayBuffer`、`Blob`、`Document`、JavaScript 对象或字符串，`responseType` 可接受 `""`、`"arraybuffer"`、`"blob"`、`"document"`、`"json"` 和 `"text"`。<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)</sup><sup> • </sup><sup>[1](https://xhr.spec.whatwg.org/)</sup> 其他属性包括 `status`（HTTP 响应状态码）、`statusText`、`timeout`（自动终止前的毫秒数）以及 `withCredentials`，后者控制跨站请求是否携带 cookie 或授权头等凭据。<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)</sup>

## 进度事件与上传

**进度监控**是 XHR 的独特能力之一。进度事件实现 `ProgressEvent` 接口，下载和上传传输都有对应的事件；下载事件在 `XMLHttpRequest` 对象本身上触发。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)</sup> 只读的 `upload` 属性返回一个 `XMLHttpRequestUpload` 对象，可以观察它来监控上传进度，其事件包括 `loadstart`、`progress`、`abort`、`error`、`load`、`timeout` 和 `loadend`。<sup>[8](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload)</sup>

给上传对象附加事件监听器有一个副作用：它会使该请求不再属于 CORS 下的“简单请求”，因此带进度跟踪的跨域上传会触发预检请求。监听器必须在 `send()` 之前注册，否则上传事件不会被派发。<sup>[8](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload)</sup>

## 同步请求及其衰落

同步 XHR 通过将 `async` 参数传为 `false` 来请求，它会阻塞主线程直到请求完成，在 Web 上经常导致卡死，尤其是在网络状况差或服务器慢的情况下。它现已被废弃，标准指出，由于对最终用户体验的有害影响，worker 之外的同步 XHR 正在从 Web 平台中移除；开发者不得在 window 上下文中为 `async` 传入 `false`。<sup>[9](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Synchronous_and_Asynchronous_Requests)</sup><sup> • </sup><sup>[1](https://xhr.spec.whatwg.org/)</sup> `timeout` 和 `abort` 等较新的 XHR 特性不允许用于同步请求，会引发 `InvalidAccessError`。<sup>[9](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Synchronous_and_Asynchronous_Requests)</sup>

2022 年 Web Almanac 测得同步 XHR 出现在 2.5% 的移动端页面和 2.8% 的桌面端页面上，份额虽小但持续存在，表明仍有遗留应用依赖这一方法。<sup>[6](https://cdn.httparchive.org/v1/static/almanac/ebooks/web_almanac_2022_en.pdf)</sup> 对于剩余的主要同步用例——在 `unload`、`beforeunload` 和 `pagehide` 事件期间发送数据——MDN 建议改用带 `keepalive` 标志的 `fetch()` 或 `navigator.sendBeacon()` API。<sup>[9](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Synchronous_and_Asynchronous_Requests)</sup> 同步请求通常不会阻塞执行的一种场景是在 Worker 内部。<sup>[9](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Synchronous_and_Asynchronous_Requests)</sup>

## 跨域请求与安全

出于安全原因，浏览器限制由脚本发起的跨域 HTTP 请求，而 `XMLHttpRequest` 遵循同源策略：Web 应用只能请求与其加载来源同源的资源，除非响应包含正确的 CORS 头，例如 `Access-Control-Allow-Origin`。<sup>[4](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS)</sup> 现代浏览器通过实现 CORS 标准来支持跨站 XHR；只要服务器配置为允许来自该应用来源的请求，请求就能成功，否则会抛出 `INVALID_ACCESS_ERR` 异常。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)</sup> CORS 机制存在的部分原因是 HTML 表单（早于 XHR 出现）本来就可以向任意来源提交简单请求，因此服务器无论如何都必须防范跨站请求伪造。<sup>[4](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS)</sup>

## XMLHttpRequest 与 fetch

Fetch API 是后来的 Web 标准，通常被视为 XHR 的现代替代品。它的主要实际优势是 `fetch()` 返回的内建 promise，避免了 XHR 基于回调的风格。<sup>[10](https://stackoverflow.com/questions/35549547/fetch-api-vs-xmlhttprequest?noredirect=1)</sup> 这种比较在两个方向上都有需要注意的地方：`fetch()` 返回的 promise 不会因 404 或 500 等 HTTP 错误状态而拒绝，因此错误处理必须显式检查 `response.status`；而且并非所有 fetch 实现都默认发送 cookie。<sup>[11](https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/)</sup>

XHR 在遗留代码库以及未通过兼容补丁支持 fetch 的环境中仍然有用武之地。<sup>[13](https://mfyz.com/xmlhttprequest-vs-fetch-which-is-the-difference-and-which-javascript-api-should-you-use/)</sup>

## 实用注意事项

绕过 HTTP 缓存的一种跨浏览器做法是在 URL 后附加时间戳，视情况使用 `?` 或 `&`；由于本地缓存以 URL 为索引，这会使每个请求都独一无二。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)</sup> 如果请求以 `status` 为 0、`statusText` 为 null 结束，说明该请求不被允许执行（`UNSENT`）；一个可能的原因是文档的来源在创建 XHR 与调用 `open()` 之间发生了变化，这在 `unload` 处理器中窗口焦点转移时可能发生。<sup>[5](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)</sup> 对于从服务器接收事件或消息数据，MDN 建议使用通过 `EventSource` 实现的服务器发送事件，全双工通信则使用 [WebSocket](https://www.edgepedia.org/zh/websockets)。<sup>[2](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)</sup>

## References

1. [XMLHttpRequest Standard, WHATWG](https://xhr.spec.whatwg.org/)
2. [XMLHttpRequest, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
3. [The Story of XMLHTTP, Alex Hopmann](https://www.alexhopmann.com/page/the-story-of-xmlhttp)
4. [Cross-Origin Resource Sharing (CORS), MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS)
5. [Using XMLHttpRequest, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)
6. [The 2022 Web Almanac by HTTP Archive](https://cdn.httparchive.org/v1/static/almanac/ebooks/web_almanac_2022_en.pdf)
7. [whatwg/web-history: Milestones in the history of the modern Web platform](https://github.com/whatwg/web-history)
8. [XMLHttpRequest: upload property, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload)
9. [Synchronous and asynchronous requests, MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Synchronous_and_Asynchronous_Requests)
10. [javascript - fetch api vs xmlhttprequest - stack overflow](https://stackoverflow.com/questions/35549547/fetch-api-vs-xmlhttprequest?noredirect=1)
11. [XMLHttpRequest vs the Fetch API for Ajax, SitePoint](https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/)
12. [What is the difference between XMLHttpRequest and fetch?, Front Prep](https://www.frontprep.com/conceptual/xmlhttprequest-vs-fetch)
13. [XMLHTTPRequest vs. Fetch: Which JavaScript API Should You Use?, mfyz](https://mfyz.com/xmlhttprequest-vs-fetch-which-is-the-difference-and-which-javascript-api-should-you-use/)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Development tools and collaboration infrastructure › Frameworks, libraries, and APIs › Web frameworks and libraries

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/xmlhttprequest

English original: https://www.edgepedia.org/xmlhttprequest
