Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

翻译正在进行中。

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);

属性

属性 类型 描述

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

注意: 在一个已经激活的request下(已经调用open()或者openRequest()方法的request)再次调用这个方法相当于调用了abort()方法。
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对象.

警告: 该方法不能在 JavaScript 代码中使用.
[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 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这个属性在所有的浏览器中都支持。

此外,在不同浏览器中实现了一系列额外的事件控制器(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) ? ? ?

相关链接

文档标签和贡献者

 最后编辑者: wangcansunking,