XMLHttpRequest 是一个API, 它为客户端提供了在客户端和服务器之间传输数据的功能。它提供了一个通过 URL 来获取数据的简单方式,并且不会使整个页面刷新。这使得网页只更新一部分页面而不会打扰到用户。XMLHttpRequest 在 AJAX 中被大量使用。
XMLHttpRequest
是一个 JavaScript 对象,它最初由微软设计,随后被 Mozilla、Apple 和 Google采纳. 如今,该对象已经被 W3C组织标准化. 通过它,你可以很容易的取回一个URL上的资源数据. 尽管名字里有XML, 但 XMLHttpRequest
可以取回所有类型的数据资源,并不局限于XML。 而且除了HTTP ,它还支持file
和 ftp
协议.
<div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">EventTarget</text></a><polyline points="111,25 121,20 121,30 111,25" stroke="#D4DDE4" fill="none"/><line x1="121" y1="25" x2="151" y2="25" stroke="#D4DDE4"/><a xlink:href="https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequestEventTarget" target="_top"><rect x="151" y="1" width="250" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="276" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">XMLHttpRequestEventTarget</text></a><polyline points="401,25 411,20 411,30 401,25" stroke="#D4DDE4" fill="none"/><line x1="411" y1="25" x2="441" y2="25" stroke="#D4DDE4"/><a xlink:href="https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest" target="_top"><rect x="441" y="1" width="140" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="511" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">XMLHttpRequest</text></a></svg></div>
a:hover text { fill: #0095DD; pointer-events: all;}
构造函数
XMLHttpRequest()
- 构造函数初始化一个XMLHttpRequest对象. 必须在所有其他方法被调用前调用构造函数。
属性
此接口继承了XMLHttpRequestEventTarget
和EventTarget
的属性。
属性 | 类型 | 描述 | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Function? |
一个JavaScript函数对象,当readyState属性改变时会调用它。回调函数会在user interface线程中调用。 警告: 不能在本地代码中使用. 也不应该在同步模式的请求中使用.
|
||||||||||||||||||
readyState |
unsigned short |
请求的五种状态
|
||||||||||||||||||
response |
varies |
响应实体的类型由 |
||||||||||||||||||
responseText |
DOMString |
此次请求的响应为文本,或是当请求未成功或还未发送时为 null。 只读。 |
||||||||||||||||||
responseType |
XMLHttpRequestResponseType |
设置该值能够改变响应类型。就是告诉服务器你期望的响应格式。
|
||||||||||||||||||
responseXML |
Document? |
本次请求的响应是一个 注意: 如果服务器不支持
text/xml Content-Type 头,你可以使用 overrideMimeType() 强制 XMLHttpRequest 将响应解析为 XML。 |
||||||||||||||||||
status |
unsigned short |
该请求的响应状态码 (例如, 状态码 200 表示一个成功的请求).只读. |
||||||||||||||||||
statusText |
DOMString |
该请求的响应状态信息,包含一个状态码和原因短语 (例如 "200 OK "). 只读. |
||||||||||||||||||
upload |
XMLHttpRequestUpload |
可以在 upload 上添加一个事件监听来跟踪上传过程。 |
||||||||||||||||||
withCredentials |
boolean |
表明在进行跨站(cross-site)的访问控制(Access-Control)请求时,是否使用认证信息(例如cookie或授权的header)。 默认为 注意: 这不会影响同站(same-site)请求.
|
非标准属性
Attribute | Type | Description |
---|---|---|
channel |
nsIChannel |
The channel used by the object when performing the request. This is null if the channel hasn't been created yet. In the case of a multi-part request, this is the initial channel, not the different parts in the multi-part request. Requires elevated privileges to access; 只读. |
mozBackgroundRequest |
boolean |
Indicates whether or not the object represents a background service request. If In cases in which a security dialog (such as authentication or a bad certificate notification) would normally be shown, the request simply fails instead. |
mozResponseArrayBuffer 已废弃 Gecko 6 |
ArrayBuffer |
The response to the request, as a JavaScript typed array. This is NULL if the request was not successful, or if it hasn't been sent yet. 只读 |
multipart |
boolean |
Indicates whether or not the response is expected to be a stream of possibly multiple XML documents. If set to This enables support for server push; for each XML document that's written to this request, a new XML DOM document is created and the 注意: When this is set, the
onload handler and other event handlers are not reset after the first XMLdocument is loaded, and the onload handler is called after each part of the response is received. |
方法
abort()
如果请求已经被发送,则立刻中止请求.
getAllResponseHeaders()
DOMString getAllResponseHeaders();
返回所有响应头信息(响应头名和值), 如果响应头还没接受,则返回null
. 注意: For multipart requests, this returns the headers from the current part of the request, not from the original channel.
getResponseHeader()
DOMString? getResponseHeader(DOMString header);
返回指定的响应头的值, 如果响应头还没被接受,或该响应头不存在,则返回null.
open()
初始化一个请求. 该方法用于JavaScript代码中;如果是本地代码, 使用 openRequest()
方法代替.
void open( DOMString method, DOMString url, optional boolean async, optional DOMString user, optional DOMString password );
参数
method
- 请求所使用的HTTP方法; 例如 "GET", "POST", "PUT", "DELETE"等. 如果下个参数是非HTTP(S)的URL,则忽略该参数.
url
- 该请求所要访问的URL
async
- 一个可选的布尔值参数,默认为true,意味着是否执行异步操作,如果值为false,则send()方法不会返回任何东西,直到接受到了服务器的返回数据。如果为值为true,一个对开发者透明的通知会发送到相关的事件监听者。这个值必须是true,如果multipart 属性是true,否则将会出现一个意外。
user
- 用户名,可选参数,为授权使用;默认参数为空string.
password
- 密码,可选参数,为授权使用;默认参数为空string.
overrideMimeType()
重写由服务器返回的MIME type。这个可用于, 例如,强制把一个响应流当作“text/xml”来处理和解析,即使服务器没有指明数据是这个类型。注意,这个方法必须在send()之前被调用。
void overrideMimeType(DOMString mimetype);
send()
发送请求. 如果该请求是异步模式(默认),该方法会立刻返回. 相反,如果请求是同步模式,则直到请求的响应完全接受以后,该方法才会返回.
send()方法之前进行
.void send(); void send(ArrayBuffer data); void send(Blob data); void send(Document data); void send(DOMString? data); void send(FormData data);
注意
If the data is a Document
, it is serialized before being sent. When sending a Document, versions of Firefox prior to version 3 always send the request using UTF-8 encoding; Firefox 3 properly sends the document using the encoding specified by body.xmlEncoding
, or UTF-8 if no encoding is specified.
If it's an nsIInputStream
, it must be compatible with nsIUploadChannel
's setUploadStream()
method. In that case, a Content-Length header is added to the request, with its value obtained using nsIInputStream
's available()
method. Any headers included at the top of the stream are treated as part of the message body. The stream's MIMEtype should be specified by setting the Content-Type header using the setRequestHeader()
method prior to calling send()
.
setRequestHeader()
给指定的HTTP请求头赋值.在这之前,你必须确认已经调用 open()
方法打开了一个url.
void setRequestHeader( DOMString header, DOMString value );
参数
header
- 将要被赋值的请求头名称.
value
- 给指定的请求头赋的值.
非标准方法
init()
在 C++代码中初始化一个XHR对象.
[noscript] void init( in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow );
参数
principal
- 主要用于请求;不可以为null.
scriptContext
- 请求上下文;不可以为null.
ownerWindow
- 和窗口相关请求; 可能为null.
openRequest()
初始化一个请求. 这个方法用于本地代码; 如果用JavaScript 代码来初始化请求, 使用 open()
代替. 看文档open()
.
sendAsBinary()
发送二进制数据 的send()
方法变种.
void sendAsBinary( in DOMString body );
参数
body
- The request body as a DOMstring. This data is converted to a string of single-byte characters by truncation (removing the high-order byte of each character).
注意
- By default, Firefox 3 limits the number of
XMLHttpRequest
connections per server to 6 (previous versions limit this to 2 per server). Some interactive web sites may keep anXMLHttpRequest
connection open, so opening multiple sessions to such sites may result in the browser hanging in such a way that the window no longer repaints and controls don't respond. This value can be changed by editing thenetwork.http.max-persistent-connections-per-server
preference inabout:config
. - From Gecko 7.0 headers set by
setRequestHeader()
are sent with the request when following a redirect. Previously these headers would not be sent. XMLHttpRequest
is implemented in Gecko using thensIXMLHttpRequest
,nsIXMLHttpRequestEventTarget
, andnsIJSXMLHttpRequest
interfaces.
Events
onreadystatechange这个属性在所有的浏览器中都支持。
此外,在不同浏览器中实现了一系列额外的事件控制器(onload,onerror,onprogress,等等)这些都在Firefox浏览器中支持。 In particular, see nsIXMLHttpRequestEventTarget
and Using XMLHttpRequest.
More recent browsers, including Firefox, also support listening to the XMLHttpRequest
events via standard addEventListener
APIs in addition to setting on*
properties to a handler function.
浏览器兼容性
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support (XHR1) | 1 | 1.0 | 5 (via ActiveXObject) 7 (XMLHttpRequest) |
(Yes) | 1.2 |
send(ArrayBuffer) | 9 | 9 | ? | 11.60 | ? |
send(Blob) | 7 | 3.6 | ? | 12 | ? |
send(FormData) | 6 | 4 | ? | 12 | ? |
response | 10 | 6 | 10 | 11.60 | ? |
responseType = 'arraybuffer' | 10 | 6 | 10 | 11.60 | ? |
responseType = 'blob' | 19 | 6 | 10 | 12 | ? |
responseType = 'document' | 18 | 11 | 未实现 | 未实现 | 未实现 |
responseType = 'json' | 未实现 | 10 | 未实现 | 12 | 未实现 |
Progress Events | 7 | 3.5 | 10 | 12 | ? |
withCredentials | 3 | 3.5 | 10 | 12 | 4 |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | ? | 0.16 | (Yes) | ? | ? | ? |
相关链接
- MDN上关于XMLHttpRequest的文章:
- XMLHttpRequest 参考,来自W3C和各浏览器制造商:
- W3C: XMLHttpRequest (base features)
- W3C: XMLHttpRequest (latest editor's draft with extensions to the base functionality, formerly XMLHttpRequest Level 2
- Microsoft documentation
- Apple developers' reference
- "Using the XMLHttpRequest Object" (jibbering.com)
- XMLHttpRequest - REST and the Rich User Experience
- HTML5 Rocks - New Tricks in XMLHttpRequest2