XMLHttpRequest

  • 版本网址缩略名: DOM/XMLHttpRequest
  • 版本标题: XMLHttpRequest
  • 版本 id: 37428
  • 创建于:
  • 创建者: ziyunfei
  • 是否是当前版本?
  • 评论 2087 words added, 771 words removed

修订内容

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?

A JavaScript function object that is called whenever the readyState attribute changes. The callback is called from the user interface thread.

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

请求的五种状态

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

The response entity body according to responseType, as an ArrayBuffer, Blob, {{ domxref("Document") }}, JavaScript object (for "json"), or string. This is null if the request is not complete or was not successful.

responseText DOMString The response to the request as text, or null if the request was unsuccessful or has not yet been sent. Read-only.
responseType XMLHttpRequestResponseType

Can be set to change the response type. This tells the server what format you want the response to be in.

Value Data type of response property
"" (empty string) String (this is the default)
"arraybuffer" ArrayBuffer
"blob" {{ domxref("Blob") }}
"document" {{ domxref("Document") }}
"json" JavaScript object, parsed from a JSON string returned by the server
"text" String
responseXML Document?

The response to the request as a DOM Document object, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. The response is parsed as if it were a text/xml stream. When the responseType is set to "document" and the request has been made asynchronously, the response is parsed as it were a text/html stream . 只读.

注意: If the server doesn't apply the text/xml Content-Type header, you can use overrideMimeType()to force XMLHttpRequest to parse it as XML anyway.
status unsigned short 该请求的响应状态码 (例如, 状态码200 表示一个成功的请求).只读.
statusText DOMString 该请求的响应状态信息,包含一个状态码和原因短语 (例如 "200 OK"). 只读.
upload XMLHttpRequestUpload The upload process can be tracked by adding an event listener to upload.
withCredentials boolean

Indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers. The default is false.

注意: 这不会影响对同一个站点的请求.

非标准属性

Attribute Type Description
channel {{ Interface("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_minversion_inline("2.0") }} {{ obsolete_inline("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().

{{ method_gecko_minversion("sendAsBinary", "1.9") }}

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 {{ manch("setRequestHeader") }} are sent with the request when following a redirect. Previously these headers would not be sent.
  • XMLHttpRequest is implemented in Gecko using the {{ interface("nsIXMLHttpRequest") }}, {{ interface("nsIXMLHttpRequestEventTarget") }}, and {{ interface("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 {{ interface("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.

浏览器兼容性

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support (XHR1) 1 1.0 5 (via ActiveXObject)
7 (XMLHttpRequest)
{{ CompatVersionUnknown() }} 1.2
send(ArrayBuffer) 9 9 {{ compatUnknown() }} 11.60 {{ compatUnknown() }}
send(Blob) 7 3.6 {{ compatUnknown() }} 12 {{ compatUnknown() }}
send(FormData) 6 4 {{ compatUnknown() }} 12 {{ compatUnknown() }}
response 10 6 10 11.60 {{ compatUnknown() }}
responseType = 'arraybuffer' 10 6 10 11.60 {{ compatUnknown() }}
responseType = 'blob' 19 6 10 12 {{ compatUnknown() }}
responseType = 'document' 18 11 {{ CompatNo() }} {{ CompatNo() }} {{ CompatNo() }}
responseType = 'json' {{ CompatNo() }} 10 {{ CompatNo() }} 12 {{ CompatNo() }}
Progress Events 7 3.5 10 12 {{ compatUnknown() }}
withCredentials 3 3.5 10 12 4
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} 0.16 {{ CompatVersionUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }} {{ CompatUnknown() }}

相关链接

{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "en": "en/DOM/XMLHttpRequest" } ) }}

修订版来源

<p><code>XMLHttpRequest</code> 是一个 <a class="internal" href="/zh-cn/JavaScript" title="zh-cn/JavaScript">JavaScript</a> 对象,它最初由微软设计,随后被 Mozilla,Apple, 和 Google采纳. 如今,该对象已经被 <a class="external" href="http://www.w3.org/TR/XMLHttpRequest/" title="http://www.w3.org/TR/XMLHttpRequest/">W3C组织标准化</a>. 通过它,你可以很容易的取回一个URL上的资源数据. 尽管名字里有XML, 但<code>XMLHttpRequest</code> 可以取回所有类型的数据资源,并不局限于XML. 而且除了<a href="/zh-cn/HTTP" title="zh-cn/HTTP">HTTP</a> ,它还支持<code>file</code> 和 <code>ftp</code> 协议.</p>
<p>创建一个 <code>XMLHttpRequest</code> 实例, 可以使用如下语句:</p>
<pre>var req = new XMLHttpRequest();
</pre>
<p> 查看文章<a class="internal" href="/zh-cn/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="zh-cn/Using XMLHttpRequest">Using XMLHttpRequest</a><code>来获取更多详细的XMLHttpRequest</code>用法.</p>
<h2>方法概述</h2>
<table class="standard-table"> <tbody> <tr> <td><code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#abort()" title="zh-cn/DOM/XMLHttpRequest#abort()">abort</a>();</code></td> </tr> <tr> <td><code>DOMString <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#getAllResponseHeaders()" title="zh-cn/DOM/XMLHttpRequest#getAllResponseHeaders()">getAllResponseHeaders</a>();</code></td> </tr> <tr> <td><code>DOMString? <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#getResponseHeader()" title="zh-cn/DOM/XMLHttpRequest#getResponseHeader()">getResponseHeader</a>(DOMString header);</code></td> </tr> <tr> <td><code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#open()" title="zh-cn/DOM/XMLHttpRequest#open()">open</a>(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);</code></td> </tr> <tr> <td><code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#overrideMimeType()" title="zh-cn/DOM/XMLHttpRequest#overrideMimeType()">overrideMimeType</a>(DOMString mime);</code></td> </tr> <tr> <td><code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#send()" title="zh-cn/DOM/XMLHttpRequest#send()">send</a>();</code><br> <code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#send()" title="zh-cn/DOM/XMLHttpRequest#send()">send</a>(ArrayBuffer data);</code><br> <code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#send()" title="zh-cn/DOM/XMLHttpRequest#send()">send</a>(Blob data);</code><br> <code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#send()" title="zh-cn/DOM/XMLHttpRequest#send()">send</a>(Document data);</code><br> <code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#send()" title="zh-cn/DOM/XMLHttpRequest#send()">send</a>(DOMString? data);</code><br> <code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#send()" title="zh-cn/DOM/XMLHttpRequest#send()">send</a>(FormData data);</code></td> </tr> <tr> <td><code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#setRequestHeader()" title="zh-cn/DOM/XMLHttpRequest#setRequestHeader()">setRequestHeader</a>(DOMString header, DOMString value);</code></td> </tr> <tr> <th>非标准方法</th> </tr> <tr> <td><code>[noscript] void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#init()" title="zh-cn/DOM/XMLHttpRequest#init()">init</a>(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);</code></td> </tr> <tr> <td><code>[noscript] void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#openRequest()" title="zh-cn/DOM/XMLHttpRequest#openRequest()">openRequest</a>(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password); </code></td> </tr> <tr> <td><code>void <a class="internal" href="/zh-cn/DOM/XMLHttpRequest#sendAsBinary()" title="zh-cn/DOM/XMLHttpRequest#sendAsBinary()">sendAsBinary</a>(in DOMString body);</code></td> </tr> </tbody>
</table>
<h2>属性</h2>
<table class="standard-table"> <tbody> <tr> <th>Attribute</th> <th>Type</th> <th>Description</th> </tr> <tr id="onreadystatechange"> <td> <p><code>onreadystatechange</code></p> </td> <td><code>Function?</code></td> <td> <p>A JavaScript function object that is called whenever the <code>readyState</code> attribute changes. The callback is called from the user interface thread.</p> <div class="warning"><strong>警告:</strong> 不能在本地代码中使用. 也不应该在同步模式的请求中使用.</div> </td> </tr> <tr id="readyState"> <td><code>readyState</code></td> <td><code>unsigned short</code></td> <td> <p>请求的五种状态</p> <table class="standard-table"> <tbody> <tr> <td class="header">值</td> <td class="header">状态</td> <td class="header">描述</td> </tr> <tr> <td><code>0</code></td> <td><code>UNSENT </code>(未打开)</td> <td><code>open()</code>方法还未被调用.</td> </tr> <tr> <td><code>1</code></td> <td><code>OPENED</code>  (未发送)</td> <td><code>send()</code>方法还未被调用.</td> </tr> <tr> <td><code>2</code></td> <td><code>HEADERS_RECEIVED (已获取响应头)</code></td> <td><code>send()</code>方法已经被调用, 响应头和响应状态已经返回.</td> </tr> <tr> <td><code>3</code></td> <td><code>LOADING (正在下载响应体)</code></td> <td>响应体下载中; <code>responseText</code>中已经获取了部分数据.</td> </tr> <tr> <td><code>4</code></td> <td><code>DONE (请求完成)</code></td> <td>整个请求过程已经完毕.</td> </tr> </tbody> </table> </td> </tr> <tr id="response"> <td><code>response</code></td> <td>varies</td> <td> <p>The response entity body according to <code><a href="#responseType">responseType</a></code>, as an <a href="/zh-cn/JavaScript_typed_arrays/ArrayBuffer" title="zh-cn/JavaScript typed arrays/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="/zh-cn/DOM/Blob" title="zh-cn/DOM/Blob"><code>Blob</code></a>, {{ domxref("Document") }}, JavaScript object (for "json"), or string. This is <code>null</code> if the request is not complete or was not successful.</p> </td> </tr> <tr id="responseText"> <td><code>responseText</code></td> <td><code>DOMString</code></td> <td>The response to the request as text, or <code>null</code> if the request was unsuccessful or has not yet been sent. <strong>Read-only.</strong></td> </tr> <tr id="responseType"> <td><code>responseType</code></td> <td><code>XMLHttpRequestResponseType</code></td> <td> <p>Can be set to change the response type. This tells the server what format you want the response to be in.</p> <table class="standard-table" style="width: auto;"> <tbody> <tr> <td class="header">Value</td> <td class="header">Data type of <code>response</code> property</td> </tr> <tr> <td><code>""</code> (empty string)</td> <td>String (this is the default)</td> </tr> <tr> <td><code>"arraybuffer"</code></td> <td><a href="/zh-cn/JavaScript_typed_arrays/ArrayBuffer" title="zh-cn/JavaScript typed arrays/ArrayBuffer"><code>ArrayBuffer</code></a></td> </tr> <tr> <td><code>"blob"</code></td> <td>{{ domxref("Blob") }}</td> </tr> <tr> <td><code>"document"</code></td> <td>{{ domxref("Document") }}</td> </tr> <tr> <td><code>"json"</code></td> <td>JavaScript object, parsed from a JSON string returned by the server</td> </tr> <tr> <td><code>"text"</code></td> <td>String</td> </tr> </tbody> </table> </td> </tr> <tr id="responseXML"> <td><code>responseXML</code></td> <td><code>Document?</code></td> <td> <p>The response to the request as a DOM <code><a class="internal" href="/zh-cn/DOM/document" title="zh-cn/DOM/Document">Document</a></code> object, or <code>null</code> if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. The response is parsed as if it were a <code>text/xml</code> stream. When the <code>responseType</code> is set to "document" and the request has been made asynchronously, the response is parsed as it were a <code>text/html</code> stream . <strong>只读</strong><strong>.</strong></p> <div class="note"><strong>注意:</strong> If the server doesn't apply the <code>text/xml</code> Content-Type header, you can use <code>overrideMimeType()</code>to force <code>XMLHttpRequest</code> to parse it as XML anyway.</div> </td> </tr> <tr id="status"> <td><code>status</code></td> <td><code>unsigned short</code></td> <td>该请求的响应状态码 (例如, <code>状态码</code>200 表示一个成功的请求).<strong>只读.</strong></td> </tr> <tr id="statusText"> <td><code>statusText</code></td> <td><code>DOMString</code></td> <td>该请求的响应状态信息,包含一个状态码和原因短语 (例如 "<code>200 OK</code>"). <strong>只读</strong><strong>.</strong></td> </tr> <tr id="upload"> <td><code>upload</code></td> <td><code>XMLHttpRequestUpload</code></td> <td>The upload process can be tracked by adding an event listener to <code>upload</code>.</td> </tr> <tr id="withCredentials"> <td><code>withCredentials</code></td> <td><code>boolean</code></td> <td> <p>Indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers. The default is <code>false</code>.</p> <div class="note"><strong>注意:</strong> 这不会影响对同一个站点的请求.</div> </td> </tr> </tbody>
</table>
<h3>非标准属性</h3>
<table class="standard-table"> <tbody> <tr> <th>Attribute</th> <th>Type</th> <th>Description</th> </tr> <tr id="channel"> <td><code>channel</code></td> <td>{{ Interface("nsIChannel") }}</td> <td>The channel used by the object when performing the request. This is <code>null</code> 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. <strong>Requires elevated privileges to access; </strong><strong>只读</strong><strong>.</strong></td> </tr> <tr id="mozBackgroundRequest"> <td><code>mozBackgroundRequest</code></td> <td><code>boolean</code></td> <td> <p>Indicates whether or not the object represents a background service request. If <code>true</code>, no load group is associated with the request, and security dialogs are prevented from being shown to the user. <strong>Requires elevated privileges to access.</strong></p> <p>In cases in which a security dialog (such as authentication or a bad certificate notification) would normally be shown, the request simply fails instead.</p> </td> </tr> <tr id="mozResponseArrayBuffer"> <td><code>mozResponseArrayBuffer</code> {{ gecko_minversion_inline("2.0") }} {{ obsolete_inline("6") }}</td> <td><a href="/zh-cn/JavaScript_typed_arrays/ArrayBuffer" title="zh-cn/JavaScript typed arrays/ArrayBuffer"><code>ArrayBuffer</code></a></td> <td>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. <strong>只读</strong></td> </tr> <tr id="multipart"> <td><code>multipart</code></td> <td><code>boolean</code></td> <td> <p>Indicates whether or not the response is expected to be a stream of possibly multiple XML documents. If set to <code>true</code>, the content type of the initial response must be <code>multipart/x-mixed-replace</code> or an error will occur. All requests must be asynchronous.</p> <p>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 <code>onload</code> handler is called between documents.</p> <div class="note"><strong>注意:</strong> When this is set, the <code>onload</code> handler and other event handlers are not reset after the first XMLdocument is loaded, and the <code>onload</code> handler is called after each part of the response is received.</div> </td> </tr> </tbody>
</table>
<h2>方法</h2>
<h3 name="abort">abort()</h3>
<p><span class="short_text" id="result_box" lang="zh-CN"><span>如果</span><span>请求已经</span><span>被发送,则立刻</span></span><span class="short_text" id="result_box" lang="zh-CN"><span>中止</span><span>请求</span><span>.</span></span></p>
<h3 name="getAllResponseHeaders">getAllResponseHeaders()</h3>
<pre>DOMString getAllResponseHeaders();
</pre>
<p>返回所有响应头信息(响应头名和值), 如果响应头还没接受,则返回<code>null</code>.<strong> 注意:</strong> For multipart requests, this returns the headers from the <em>current</em> part of the request, not from the original channel.</p>
<h3 name="getResponseHeader">getResponseHeader()</h3>
<pre>DOMString? getResponseHeader(DOMString <var>header</var>);
</pre>
<p>返回指定的响应头的值, 如果响应头还没被接受,或该响应头不存在,则返回null.</p>
<h3 name="open">open()</h3>
<p>初始化一个请求. 该方法用于JavaScript代码中;如果是<span class="st">本地代码</span>, 使用 <a class="internal" href="/zh-cn/nsIXMLHttpRequest#openRequest()" title="/zh-cn/XMLHttpRequest#openRequest()"><code>openRequest()</code></a>方法代替.</p>
<div class="note"><strong>注意:</strong> Calling this method an already active request (one for which <code>open()</code>or <code>openRequest()</code>has already been called) is the equivalent of calling <code>abort()</code>.</div>
<pre>void open(
   DOMString <var>method</var>,
   DOMString <var>url</var>,
   optional boolean <var>async</var>,
   optional DOMString <var>user</var>,
   optional DOMString <var>password</var>
);
</pre>
<h6>参数</h6>
<dl> <dt><code>method</code></dt> <dd>请求所使用的HTTP方法; "POST" 或者 "GET". 如果下个参数是非HTTP(S)的URL,则忽略该参数.</dd> <dt><code>url</code></dt> <dd>该请求所要访问的URL</dd> <dt><code>async</code></dt> <dd>An optional boolean parameter, defaulting to <code>true</code>, indicating whether or not to perform the operation asynchronously. If this value is <code>false</code>, the <code>send()</code>method does not return until the response is received. If <code>true</code>, notification of a completed transaction is provided using event listeners. This <em>must</em> be true if the <code>multipart</code> attribute is <code>true</code>, or an exception will be thrown.</dd> <dt><code>user</code></dt> <dd>The optional user name to use for authentication purposes; by default, this is an empty string.</dd> <dt><code>password</code></dt> <dd>The optional password to use for authentication purposes; by default, this is an empty string.</dd>
</dl>
<h3 name="overrideMimeType">overrideMimeType()</h3>
<p>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 <code>send()</code>.</p>
<pre>void overrideMimeType(DOMString <var>mimetype</var>);</pre>
<h3 name="send">send()</h3>
<p>发送请求. 如果该请求是异步模式(默认),该方法会立刻返回. 相反,如果请求是同步模式,则直到请求的响应完全接受以后,该方法才会返回.</p>
<div class="note"><strong>注意:</strong> 所有相关的事件绑定必须在调用<code>send()方法之前进行</code>.</div>
<pre>void send();
void send(ArrayBuffer <var>data</var>);
void send(Blob <var>data</var>);
void send(Document <var>data</var>);
void send(DOMString? <var>data</var>);
void send(FormData <var>data</var>);</pre>
<h4>注意</h4>
<p>If the <var>data</var> is a <code>Document</code>, 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; <a href="/zh-cn/Firefox_3" rel="internal" title="zh-cn/Firefox_3">Firefox 3</a> properly sends the document using the encoding specified by <code>body.xmlEncoding</code>, or UTF-8 if no encoding is specified.</p>
<p>If it's an <code>nsIInputStream</code>, it must be compatible with <code>nsIUploadChannel</code>'s <code>setUploadStream()</code>method. In that case, a Content-Length header is added to the request, with its value obtained using <code>nsIInputStream</code>'s <code>available()</code>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 <a class="internal" href="/zh-cn/nsIXMLHttpRequest#setRequestHeader()" title="/zh-cn/XMLHttpRequest#setRequestHeader()"><code>setRequestHeader()</code></a>method prior to calling <code>send()</code>.</p>
<h3 name="setRequestHeader">setRequestHeader()</h3>
<p>给指定的HTTP请求头赋值.在这之前,你必须确认已经调用 <a href="#open"><code>open()</code></a> 方法打开了一个url.</p>
<pre>void setRequestHeader(
   DOMString <var>header</var>,
   DOMString <var>value</var>
);
</pre>
<h4>参数</h4>
<dl> <dt><code>header</code></dt> <dd>将要被赋值的请求头名称.</dd> <dt><code>value</code></dt> <dd>给指定的请求头赋的值.</dd>
</dl>
<h3>非标准方法</h3>
<h4>init()</h4>
<p>在 C++代码中初始化一个XHR对象.</p>
<div class="warning"><strong>警告:</strong> 该方法不能在 JavaScript 代码中使用.</div>
<pre>[noscript] void init(
   in nsIPrincipal principal,
   in nsIScriptContext scriptContext,
   in nsPIDOMWindow ownerWindow
);
</pre>
<h5>参数</h5>
<dl> <dt><code>principal</code></dt> <dd>The principal to use for the request; must not be <code>null</code>.</dd> <dt><code>scriptContext</code></dt> <dd>The script context to use for the request; must not be <code>null</code>.</dd> <dt><code>ownerWindow</code></dt> <dd>The window associated with the request; may be <code>null</code>.</dd>
</dl>
<h4>openRequest()</h4>
<p>Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use <a class="internal" href="/zh-cn/nsIXMLHttpRequest#open()" title="/zh-cn/XMLHttpRequest#open()"><code>open()</code></a>instead. See the documentation for <code>open()</code>.</p>
<p>{{ method_gecko_minversion("sendAsBinary", "1.9") }}</p>
<p>A variant of the <code>send()</code>method that sends binary data.</p>
<pre>void sendAsBinary(
   in DOMString body
);
</pre>
<h5>参数</h5>
<dl> <dt><code>body</code></dt> <dd>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).</dd>
</dl>
<h2>注意</h2>
<ul> <li class="note">By default, Firefox 3 limits the number of <code>XMLHttpRequest</code> connections per server to 6 (previous versions limit this to 2 per server). Some interactive web sites may keep an <code>XMLHttpRequest</code> 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 <code>network.http.max-persistent-connections-per-server</code> preference in <code><a class="linkification-ext" href="/about:config" title="Linkification: about:config">about:config</a></code>.</li> <li class="note">From {{ gecko("7.0") }} headers set by {{ manch("setRequestHeader") }} are sent with the request when following a redirect. Previously these headers would not be sent.</li> <li class="note"><code>XMLHttpRequest</code> is implemented in Gecko using the {{ interface("nsIXMLHttpRequest") }}, {{ interface("nsIXMLHttpRequestEventTarget") }}, and {{ interface("nsIJSXMLHttpRequest") }} interfaces.</li>
</ul>
<h4 class="note">Events</h4>
<p><code>onreadystatechange</code> as a property on the xhr object is supported in all browsers.</p>
<p>Since then, a number of additional event handlers were implemented in various browsers (<code>onload</code>, <code>onerror</code>, <code>onprogress</code>, etc.). These are supported in Firefox. In particular, see {{ interface("nsIXMLHttpRequestEventTarget") }} and <a href="/zh-cn/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="zh-cn/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a>.</p>
<p>More recent browsers, including Firefox, also support listening to the <code>XMLHttpRequest</code> events via standard <code><a href="/zh-cn/DOM/element.addEventListener" title="element.addEventListener">addEventListener</a></code> APIs in addition to setting <code>on*</code> properties to a handler function.</p>
<h2 name="Browser_Compatibility">浏览器兼容性</h2>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop"> <table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Chrome</th> <th>Firefox (Gecko)</th> <th>Internet Explorer</th> <th>Opera</th> <th>Safari (WebKit)</th> </tr> <tr> <td>Basic support (XHR1)</td> <td>1</td> <td>1.0</td> <td>5 (via ActiveXObject)<br> 7 (XMLHttpRequest)</td> <td>{{ CompatVersionUnknown() }}</td> <td>1.2</td> </tr> <tr> <td>send(ArrayBuffer)</td> <td>9</td> <td>9</td> <td>{{ compatUnknown() }}</td> <td>11.60</td> <td>{{ compatUnknown() }}</td> </tr> <tr> <td>send(Blob)</td> <td>7</td> <td>3.6</td> <td>{{ compatUnknown() }}</td> <td>12</td> <td>{{ compatUnknown() }}</td> </tr> <tr> <td>send(FormData)</td> <td>6</td> <td>4</td> <td>{{ compatUnknown() }}</td> <td>12</td> <td>{{ compatUnknown() }}</td> </tr> <tr> <td>response</td> <td>10</td> <td>6</td> <td>10</td> <td>11.60</td> <td>{{ compatUnknown() }}</td> </tr> <tr> <td>responseType = 'arraybuffer'</td> <td>10</td> <td>6</td> <td>10</td> <td>11.60</td> <td>{{ compatUnknown() }}</td> </tr> <tr> <td>responseType = 'blob'</td> <td>19</td> <td>6</td> <td>10</td> <td>12</td> <td>{{ compatUnknown() }}</td> </tr> <tr> <td>responseType = 'document'</td> <td>18</td> <td>11</td> <td>{{ CompatNo() }}</td> <td>{{ CompatNo() }}</td> <td>{{ CompatNo() }}</td> </tr> <tr> <td>responseType = 'json'</td> <td>{{ CompatNo() }}</td> <td>10</td> <td>{{ CompatNo() }}</td> <td>12</td> <td>{{ CompatNo() }}</td> </tr> <tr> <td>Progress Events</td> <td>7</td> <td>3.5</td> <td>10</td> <td>12</td> <td>{{ compatUnknown() }}</td> </tr> <tr> <td>withCredentials</td> <td>3</td> <td>3.5</td> <td>10</td> <td>12</td> <td>4</td> </tr> </tbody> </table>
</div>
<div id="compat-mobile"> <table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Android</th> <th>Chrome for Android</th> <th>Firefox Mobile (Gecko)</th> <th>IE Phone</th> <th>Opera Mobile</th> <th>Safari Mobile</th> </tr> <tr> <td>Basic support</td> <td>{{ CompatUnknown() }}</td> <td>0.16</td> <td>{{ CompatVersionUnknown() }}</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> <td>{{ CompatUnknown() }}</td> </tr> </tbody> </table>
</div>
<h2>相关链接</h2>
<ul> <li>MDN上关于XMLHttpRequest的文章: <ul> <li><a href="/zh-cn/AJAX/Getting_Started" title="zh-cn/AJAX/Getting_Started">AJAX - Getting Started</a></li> <li><a href="/zh-cn/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="zh-cn/Using XMLHttpRequest">Using XMLHttpRequest</a></li> <li><a href="/zh-cn/HTML_in_XMLHttpRequest" title="zh-cn/HTML_in_XMLHttpRequest">HTML in XMLHttpRequest</a></li> <li><a href="/zh-cn/DOM/XMLHttpRequest/FormData" title="zh-cn/XMLHttpRequest/FormData"><code>FormData</code></a></li> </ul> </li> <li>XMLHttpRequest 参考,来自W3C和各浏览器制造商: <ul> <li><a class="external" href="http://www.w3.org/TR/XMLHttpRequest1/">W3C: XMLHttpRequest</a> (base features)</li> <li><a class="external" href="http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html" title="http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html">W3C: XMLHttpRequest</a> (latest editor's draft with extensions to the base functionality, formerly XMLHttpRequest Level 2</li> <li><a class="external" href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmobjxmlhttprequest.asp">Microsoft documentation</a></li> <li><a class="external" href="http://developer.apple.com/internet/webcontent/xmlhttpreq.html">Apple developers' reference</a></li> </ul> </li> <li><a class="external" href="http://jibbering.com/2002/4/httprequest.html">"Using the XMLHttpRequest Object" (jibbering.com)</a></li> <li><a class="external" href="http://www.peej.co.uk/articles/rich-user-experience.html">XMLHttpRequest - REST and the Rich User Experience</a></li> <li><a class="external" href="http://www.html5rocks.com/zh-cn/tutorials/file/xhr2/">HTML5 Rocks - New Tricks in XMLHttpRequest2</a></li>
</ul>
<p>{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "en": "en/DOM/XMLHttpRequest" } ) }}</p>
恢复到这个版本