XMLHttpRequest

XMLHttpRequest 是一个 JavaScript 对象,它最初由微软设计,随后被 Mozilla,Apple, 和 Google采纳. 如今,该对象已经被 W3C组织标准化. 通过它,你可以很容易的取回一个URL上的资源数据. 尽管名字里有XML, 但XMLHttpRequest 可以取回所有类型的数据资源,并不局限于XML. 而且除了HTTP ,它还支持fileftp 协议.

创建一个 XMLHttpRequest 实例, 可以使用如下语句:

var req = new XMLHttpRequest();

 查看文章Using XMLHttpRequest来获取更多详细的XMLHttpRequest用法.

方法概述

void abort();
DOMString getAllResponseHeaders();
DOMString? getResponseHeader(DOMString header);
void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
void overrideMimeType(DOMString mime);
void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
void setRequestHeader(DOMString header, DOMString value);
非标准方法
[noscript] void init(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);
[noscript] void openRequest(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);
void sendAsBinary(in DOMString body);

属性

Attribute Type Description

onreadystatechange

Function?

一个JavaScript函数对象,当readyState属性改变时会调用它。回调函数会在user interface线程中调用。

警告: 不能在本地代码中使用. 也不应该在同步模式的请求中使用.
readyState unsigned short

请求的五种状态

状态 描述
0 UNSENT (未打开) open()方法还未被调用.
1 OPENED  (未发送) send()方法还未被调用.
2 HEADERS_RECEIVED (已获取响应头) send()方法已经被调用, 响应头和响应状态已经返回.
3 LOADING (正在下载响应体) 响应体下载中; responseText中已经获取了部分数据.
4 DONE (请求完成) 整个请求过程已经完毕.
response varies

响应实体的类型由 responseType 来指定, 可以是 ArrayBuffer Blob Document, JavaScript 对象 (即 "json"), 或者是字符串。如果请求未完成或失败,则该值为 null。

responseText DOMString 此次请求的响应为文本,或是当请求未成功或还未发送时为 null。只读。
responseType XMLHttpRequestResponseType

设置该值能够改变响应类型。就是告诉服务器你期望的响应格式。

Value Data type of response property
"" (空字符串) 字符串(默认值)
"arraybuffer" ArrayBuffer
"blob" Blob
"document" Document
"json" JavaScript 对象,解析自服务器传递回来的JSON 字符串。
"text" 字符串
responseXML Document?

本次请求的响应是一个 Document 对象,如果是以下情况则值为 null:请求未成功,请求未发送,或响应无法被解析成 XML 或 HTML。当响应为text/xml 流时会被解析。当 responseType 设置为"document",并且请求为异步的,则响应会被当做 text/html 流来解析。只读.

注意: 如果服务器不支持 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)。 默认为 false。

注意: 这不会影响同站(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 true, no load group is associated with the request, and security dialogs are prevented from being shown to the user. Requires elevated privileges to access.

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 true, the content type of the initial response must be multipart/x-mixed-replace or an error will occur. All requests must be asynchronous.

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 onload handler is called between documents.

注意: 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()方法代替.

注意: Calling this method an already active request (one for which open()or openRequest()has already been called) is the equivalent of calling abort().
void open(
   DOMString method,
   DOMString url,
   optional boolean async,
   optional DOMString user,
   optional DOMString password
);
参数
method
请求所使用的HTTP方法; "POST" 或者 "GET". 如果下个参数是非HTTP(S)的URL,则忽略该参数.
url
该请求所要访问的URL
async
An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send()method does not return until the response is received. If true, notification of a completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or an exception will be thrown.
user
The optional user name to use for authentication purposes; by default, this is an empty string.
password
The optional password to use for authentication purposes; by default, this is an empty string.

overrideMimeType()

Overrides the MIME type returned by the server. This may be used, for example, to force a stream to be treated and parsed as text/xml, even if the server does not report it as such.This method must be called before 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对象.

警告: 该方法不能在 JavaScript 代码中使用.
[noscript] void init(
   in nsIPrincipal principal,
   in nsIScriptContext scriptContext,
   in nsPIDOMWindow ownerWindow
);
参数
principal
The principal to use for the request; must not be null.
scriptContext
The script context to use for the request; must not be null.
ownerWindow
The window associated with the request; may be null.

openRequest()

Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open()instead. See the documentation for open().

Requires Gecko 1.9 (Firefox 3)

sendAsBinary()

A variant of the send()method that sends binary data.

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 an XMLHttpRequest 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 the network.http.max-persistent-connections-per-server preference in about: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 the nsIXMLHttpRequest, nsIXMLHttpRequestEventTarget, and nsIJSXMLHttpRequest interfaces.

Events

onreadystatechange as a property on the xhr object is supported in all browsers.

Since then, a number of additional event handlers were implemented in various browsers (onload, onerror, onprogress, etc.). These are supported in 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 Not supported Not supported Not supported
responseType = 'json' Not supported 10 Not supported 12 Not supported
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) ? ? ?

相关链接

Document Tags and Contributors

Contributors to this page: ziyunfei, Carrie zhxj, Kook pudding, sunnylost, hanzhao
最后编辑者: ziyunfei,