From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../zh-cn/web/api/xmlhttprequest/abort/index.html | 62 ++ .../web/api/xmlhttprequest/abort_event/index.html | 146 ++++ .../web/api/xmlhttprequest/channel/index.html | 12 + .../web/api/xmlhttprequest/error_event/index.html | 139 ++++ .../getallresponseheaders/index.html | 83 +++ .../xmlhttprequest/getresponseheader/index.html | 141 ++++ .../html_in_xmlhttprequest/index.html | 194 +++++ files/zh-cn/web/api/xmlhttprequest/index.html | 192 +++++ .../web/api/xmlhttprequest/load_event/index.html | 142 ++++ .../web/api/xmlhttprequest/mozanon/index.html | 16 + .../xmlhttprequest/mozbackgroundrequest/index.html | 18 + .../mozresponsearraybuffer/index.html | 12 + .../web/api/xmlhttprequest/mozsystem/index.html | 10 + .../xmlhttprequest/onreadystatechange/index.html | 120 +++ files/zh-cn/web/api/xmlhttprequest/open/index.html | 114 +++ .../web/api/xmlhttprequest/openrequest/index.html | 8 + .../api/xmlhttprequest/overridemimetype/index.html | 68 ++ .../web/api/xmlhttprequest/readystate/index.html | 109 +++ .../web/api/xmlhttprequest/response/index.html | 93 +++ .../web/api/xmlhttprequest/responsetext/index.html | 114 +++ .../web/api/xmlhttprequest/responsetype/index.html | 47 ++ .../web/api/xmlhttprequest/responseurl/index.html | 90 +++ .../web/api/xmlhttprequest/responsexml/index.html | 135 ++++ files/zh-cn/web/api/xmlhttprequest/send/index.html | 261 +++++++ .../sending_and_receiving_binary_data/index.html | 153 ++++ .../api/xmlhttprequest/setrequestheader/index.html | 109 +++ .../zh-cn/web/api/xmlhttprequest/status/index.html | 79 ++ .../web/api/xmlhttprequest/statustext/index.html | 70 ++ .../index.html | 237 ++++++ .../web/api/xmlhttprequest/timeout/index.html | 53 ++ .../api/xmlhttprequest/timeout_event/index.html | 128 ++++ .../zh-cn/web/api/xmlhttprequest/upload/index.html | 116 +++ .../xmlhttprequest/using_xmlhttprequest/index.html | 807 +++++++++++++++++++++ .../using_xmlhttprequest_in_ie6/index.html | 28 + .../api/xmlhttprequest/withcredentials/index.html | 103 +++ .../api/xmlhttprequest/xmlhttprequest/index.html | 58 ++ 36 files changed, 4267 insertions(+) create mode 100644 files/zh-cn/web/api/xmlhttprequest/abort/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/abort_event/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/channel/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/error_event/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/getallresponseheaders/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/getresponseheader/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/html_in_xmlhttprequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/load_event/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/mozanon/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/mozbackgroundrequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/mozresponsearraybuffer/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/mozsystem/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/onreadystatechange/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/open/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/openrequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/overridemimetype/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/readystate/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/response/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/responsetext/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/responsetype/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/responseurl/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/responsexml/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/send/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/sending_and_receiving_binary_data/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/setrequestheader/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/status/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/statustext/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/timeout/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/timeout_event/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/upload/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest_in_ie6/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/withcredentials/index.html create mode 100644 files/zh-cn/web/api/xmlhttprequest/xmlhttprequest/index.html (limited to 'files/zh-cn/web/api/xmlhttprequest') diff --git a/files/zh-cn/web/api/xmlhttprequest/abort/index.html b/files/zh-cn/web/api/xmlhttprequest/abort/index.html new file mode 100644 index 0000000000..d98eabf064 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/abort/index.html @@ -0,0 +1,62 @@ +--- +title: XMLHttpRequest.abort() +slug: Web/API/XMLHttpRequest/abort +tags: + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/abort +--- +

{{APIRef('XMLHttpRequest')}}

+ +

如果该请求已被发出,XMLHttpRequest.abort() 方法将终止该请求。当一个请求被终止,它的  {{domxref("XMLHttpRequest.readyState", "readyState")}} 将被置为 {{domxref("XMLHttpRequest.UNSENT")}} (0),并且请求的 {{domxref("XMLHttpRequest.status", "status")}} 置为 0。

+ +

语法

+ +
xhrInstance.abort();
+ +

参数

+ +

无。

+ +

返回值

+ +

undefined

+ +

示例

+ +
var xhr = new XMLHttpRequest(),
+    method = "GET",
+    url = "https://developer.mozilla.org/";
+xhr.open(method, url, true);
+
+xhr.send();
+
+if (OH_NOES_WE_NEED_TO_CANCEL_RIGHT_NOW_OR_ELSE) {
+  xhr.abort();
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-abort()-method')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{Compat("api.XMLHttpRequest.abort")}}
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/abort_event/index.html b/files/zh-cn/web/api/xmlhttprequest/abort_event/index.html new file mode 100644 index 0000000000..9bdad07e9d --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/abort_event/index.html @@ -0,0 +1,146 @@ +--- +title: 'XMLHttpRequest: abort event' +slug: Web/API/XMLHttpRequest/abort_event +tags: + - XMLHttpRequest + - abort +translation_of: Web/API/XMLHttpRequest/abort_event +--- +
{{APIRef}}
+ +
+ +
当一个请求终止时 abort 事件被触发,比如程序执行 {{domxref("XMLHttpRequest.abort()")}}。
+ +
+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("ProgressEvent")}}
Event handler property{{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}}
+ +

Examples

+ +

Live example

+ +

HTML

+ +
<div class="controls">
+    <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" />
+    <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" />
+    <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" />
+</div>
+
+<textarea readonly class="event-log"></textarea>
+ + + +

JS

+ +
const xhrButtonSuccess = document.querySelector('.xhr.success');
+const xhrButtonError = document.querySelector('.xhr.error');
+const xhrButtonAbort = document.querySelector('.xhr.abort');
+const log = document.querySelector('.event-log');
+
+function handleEvent(e) {
+    log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`;
+}
+
+function addListeners(xhr) {
+    xhr.addEventListener('loadstart', handleEvent);
+    xhr.addEventListener('load', handleEvent);
+    xhr.addEventListener('loadend', handleEvent);
+    xhr.addEventListener('progress', handleEvent);
+    xhr.addEventListener('error', handleEvent);
+    xhr.addEventListener('abort', handleEvent);
+}
+
+function runXHR(url) {
+    log.textContent = '';
+
+    const xhr = new XMLHttpRequest();
+    addListeners(xhr);
+    xhr.open("GET", url);
+    xhr.send();
+    return xhr;
+}
+
+xhrButtonSuccess.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg');
+});
+
+xhrButtonError.addEventListener('click', () => {
+    runXHR('https://somewhere.org/i-dont-exist');
+});
+
+xhrButtonAbort.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort();
+});
+ +

Result

+ +

{{ EmbedLiveSample('Live_example', '100%', '150px') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#event-xhr-abort')}}{{Spec2('XMLHttpRequest')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.XMLHttpRequest.abort_event")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/channel/index.html b/files/zh-cn/web/api/xmlhttprequest/channel/index.html new file mode 100644 index 0000000000..f95b595f2c --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/channel/index.html @@ -0,0 +1,12 @@ +--- +title: XMLHttpRequest.channel +slug: Web/API/XMLHttpRequest/channel +translation_of: Web/API/XMLHttpRequest/channel +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +

创建请求的时候, XMLHttpRequest.channel  是一个被对象使用的  nsIChannel 。如果管道(channel) 还没被创建的话,它的值是 null 。在一个 multi-part  请求案例中,它是初始化的管道,不是 multi-part 请求中的不同部分。

+ +

需要权限提升。

+ +

 

diff --git a/files/zh-cn/web/api/xmlhttprequest/error_event/index.html b/files/zh-cn/web/api/xmlhttprequest/error_event/index.html new file mode 100644 index 0000000000..e92ec4bb65 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/error_event/index.html @@ -0,0 +1,139 @@ +--- +title: 'XMLHttpRequest: error 事件' +slug: Web/API/XMLHttpRequest/error_event +translation_of: Web/API/XMLHttpRequest/error_event +--- +
{{APIRef}}
+ +

当请求遇到错误时,将触发error 事件。

+ + + + + + + + + + + + + + + + + + + + +
可冒泡No
可取消No
接口{{domxref("ProgressEvent")}}
事件处理程序属性{{domxref("XMLHttpRequestEventTarget/onerror", "onerror")}}
+ +

示例

+ +

在线示例

+ +

HTML

+ +
<div class="controls">
+    <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" />
+    <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" />
+    <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" />
+</div>
+
+<textarea readonly class="event-log"></textarea>
+ + + +

JS

+ +
const xhrButtonSuccess = document.querySelector('.xhr.success');
+const xhrButtonError = document.querySelector('.xhr.error');
+const xhrButtonAbort = document.querySelector('.xhr.abort');
+const log = document.querySelector('.event-log');
+
+function handleEvent(e) {
+    log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`;
+}
+
+function addListeners(xhr) {
+    xhr.addEventListener('loadstart', handleEvent);
+    xhr.addEventListener('load', handleEvent);
+    xhr.addEventListener('loadend', handleEvent);
+    xhr.addEventListener('progress', handleEvent);
+    xhr.addEventListener('error', handleEvent);
+    xhr.addEventListener('abort', handleEvent);
+}
+
+function runXHR(url) {
+    log.textContent = '';
+
+    const xhr = new XMLHttpRequest();
+    addListeners(xhr);
+    xhr.open("GET", url);
+    xhr.send();
+    return xhr;
+}
+
+xhrButtonSuccess.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg');
+});
+
+xhrButtonError.addEventListener('click', () => {
+    runXHR('https://somewhere.org/i-dont-exist');
+});
+
+xhrButtonAbort.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort();
+});
+ +

结果

+ +

{{ EmbedLiveSample('在线示例', '100%', '150px') }}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#event-xhr-error')}}{{Spec2('XMLHttpRequest')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.error_event")}}

+ +

其他

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/getallresponseheaders/index.html b/files/zh-cn/web/api/xmlhttprequest/getallresponseheaders/index.html new file mode 100644 index 0000000000..5c12e95526 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/getallresponseheaders/index.html @@ -0,0 +1,83 @@ +--- +title: XMLHttpRequest.getAllResponseHeaders() +slug: Web/API/XMLHttpRequest/getAllResponseHeaders +translation_of: Web/API/XMLHttpRequest/getAllResponseHeaders +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.getAllResponseHeaders() 方法返回所有的响应头,以 {{Glossary('CRLF')}} 分割的字符串,或者 null 如果没有收到任何响应。 注意: 对于复合请求 ( multipart requests ),这个方法返回当前请求的头部,而不是最初的请求的头部。

+ +
DOMString getAllResponseHeaders();
+ +

语法

+ +
var headers = XMLHttpRequest.getAllResponseHeaders();
+
+ +

参数

+ +

无。

+ +

返回值

+ +

一个原始的header头例子:

+ +
date: Fri, 08 Dec 2017 21:04:30 GMT\r\n
+content-encoding: gzip\r\n
+x-content-type-options: nosniff\r\n
+server: meinheld/0.6.1\r\n
+x-frame-options: DENY\r\n
+content-type: text/html; charset=utf-8\r\n
+connection: keep-alive\r\n
+strict-transport-security: max-age=63072000\r\n
+vary: Cookie, Accept-Encoding\r\n
+content-length: 6502\r\n
+x-xss-protection: 1; mode=block\r\n
+
+ +

每一行通过\r\n来进行分割。

+ +

例子

+ +
var request = new XMLHttpRequest();
+request.open("GET", "foo.txt", true);
+request.send();
+
+request.onreadystatechange = function() {
+  if(this.readyState == this.HEADERS_RECEIVED) {
+
+    // Get the raw header string
+    var headers = request.getAllResponseHeaders();
+
+    // Convert the header string into an array
+    // of individual headers
+    var arr = headers.trim().split(/[\r\n]+/);
+
+    // Create a map of header names to values
+    var headerMap = {};
+    arr.forEach(function (line) {
+      var parts = line.split(': ');
+      var header = parts.shift();
+      var value = parts.join(': ');
+      headerMap[header] = value;
+    });
+  }
+
+
+ +

上面的代码执行后,你可以:

+ +
var contentType = headerMap["content-type"];
+
+ +

上面的变量contentType可以获取到http header里的content-type字段值。

+ +

 

+ +

 

+ +

 

+ +

 

+ +

 

diff --git a/files/zh-cn/web/api/xmlhttprequest/getresponseheader/index.html b/files/zh-cn/web/api/xmlhttprequest/getresponseheader/index.html new file mode 100644 index 0000000000..e447182f2b --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/getresponseheader/index.html @@ -0,0 +1,141 @@ +--- +title: XMLHttpRequest.getResponseHeader() +slug: Web/API/XMLHttpRequest/getResponseHeader +tags: + - API + - HTTP协议 + - XHR头 + - XHR请求 + - XMLHttpRequest + - getResponseHeader + - http头 + - 引用 + - 得到响应头 + - 报文 + - 方法 +translation_of: Web/API/XMLHttpRequest/getResponseHeader +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.getResponseHeader()方法返回包含指定响应头文本的字符串。

+ +

如果在返回的响应头中有多个一样的名称,那么返回的值就会是用逗号和空格将值分隔的字符串。getResponseHeader()方法以UTF编码返回值。搜索的报文名是不区分大小写的。

+ +

语法

+ +
var myHeader = XMLHttpRequest.getResponseHeader(name);
+ +

参数

+ +
+
name
+
一个字符串,表示要返回的报文项名称。
+
+ +

返回值

+ +

报文项值,如果连接未完成,响应中不存在报文项,或者被W3C限制,则返回null。

+ +

示例:

+ +
var client = new XMLHttpRequest();//新建XMLHttpRequest对象。
+client.open("GET", "somefile.txt", true);//采用异步,GET方式获取somefile.txt。
+client.send();//发送空的query string。
+client.onreadystatechange = function() {//设定侦听器onreadystatechange。
+  if(this.readyState == this.HEADERS_RECEIVED) {//如果readyState表示响应头已返回
+    var contentType=client.getResponseHeader("Content-Type"));//将此连接的Content-Type响应头项赋值到contentType。
+    if(contentType != my_expected_type) {//如果这不是你的预期值
+      client.abort();//终止连接
+    }
+  }
+}
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#dom-xmlhttprequest-getresponseheader', 'getResponseHeader()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
浏览器ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基础支持{{CompatChrome(1)}}{{CompatVersionUnknown}}{{CompatUnknown}}[1]{{CompatIe('5')}}[2]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
+

浏览器

+
AndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基础支持{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1]从Firefox 49开始,在首选项network.http.keep_empty_response_headers_as_empty_string设置为true的情况下,空响应头将作为空字符串返回,默认为false。 在Firefox 49之前,空响应头已被忽略。从Firefox 50开始,该项默认设置为true。

+ +

[2]该功能最开始是通过ActiveXObject()实现的。 直到Internet Explorer 7,标准的XMLHttpRequest才出现。

+ +

也请看看:

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/html_in_xmlhttprequest/index.html b/files/zh-cn/web/api/xmlhttprequest/html_in_xmlhttprequest/index.html new file mode 100644 index 0000000000..74e8cac761 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/html_in_xmlhttprequest/index.html @@ -0,0 +1,194 @@ +--- +title: HTML in XMLHttpRequest +slug: Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest +--- +

W3C {{domxref("XMLHttpRequest")}} 规范为 XMLHttpRequest添加HTML语法解析功能, 此前仅支持XML语法解析。该功能允许Web应用程序使用XMLHttpRequest作为解析的DOM。

+ +

局限

+ +

为了阻止同步使用XMLHttpRequest,HTML在同步模式下不支持使用。并且,只有当responseType属性设置为'document'的情况下,HTML支持才可用。这种限制避免了浪费时间解析HTML,而传统代码在默认模式下使用XMLHttpRequest来检索text/html资源的responseText. 此外,该限制避免了遗留代码的问题,该代码假定Http错误页面(通常具有text/html响应正文)的responseXML为空。

+ +

用法

+ +

使用XMLHttpRequest将HTML资源恢复为DOM就像使用XMLHttpRequest将XML资源恢复为DOM一样,除了您不能使用同步模式,您必须通过将字符串“document”分配给responseType属性来显式请求文档调用open()之后调用send()之前的XMLHttpRequest对象。

+ +

 

+ +
var xhr = new XMLHttpRequest();
+xhr.onload = function() {
+  console.log(this.responseXML.title);
+}
+xhr.open("GET", "file.html");
+xhr.responseType = "document";
+xhr.send();
+
+ +

功能检测

+ +

方法1

+ +

该方法依赖于功能的“强制异步”性质。当你尝试设置一个以“sync”方式打开的XMLHttpRequest对象后,尝试将设置responseType会在实现该功能的浏览器上引发错误,其他浏览器则运行良好。

+ +
+
function HTMLinXHR() {
+  if (!window.XMLHttpRequest)
+    return false;
+  var req = new window.XMLHttpRequest();
+  req.open('GET', window.location.href, false);
+  try {
+    req.responseType = 'document';
+  } catch(e) {
+    return true;
+  }
+  return false;
+}
+
+
+ +

在JSFiddle中查看

+ +

This method is synchronous, does not rely on external assets though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of that feature.

+ +

方法2

+ +

 

+ +

检测浏览器是否支持XMLHttpRequest中的HTML解析有两个挑战。首先,检测结果是异步获取的,因为HTML支持仅在异步模式下可用。Second, you have to actually fetch a test document over HTTP, because testing with a data: URL would end up testing data:URL support at the same time.

+ +

因此,为了检测HTML支持,服务器上需要一个测试HTML文件。这个测试文件很小,格式不是很完整:

+ +
<title>&amp;&<</title>
+ +

如果文件名为detect.html,以下功能可用于检测HTML解析支持:

+ +
function detectHtmlInXhr(callback) {
+  if (!window.XMLHttpRequest) {
+    window.setTimeout(function() { callback(false); }, 0);
+    return;
+  }
+  var done = false;
+  var xhr = new window.XMLHttpRequest();
+  xhr.onreadystatechange = function() {
+    if (this.readyState == 4 && !done) {
+      done = true;
+      callback(!!(this.responseXML && this.responseXML.title && this.responseXML.title == "&&<"));
+    }
+  }
+  xhr.onabort = xhr.onerror = function() {
+    if (!done) {
+      done = true;
+      callback(false);
+    }
+  }
+  try {
+    xhr.open("GET", "detect.html");
+    xhr.responseType = "document";
+    xhr.send();
+  } catch (e) {
+    window.setTimeout(function() {
+      if (!done) {
+        done = true;
+        callback(false);
+      }
+    }, 0);
+  }
+}
+
+ +

参数callback是一个函数,如果HTML解析是支持的,则将以true作为唯一参数被异步调用,如果不支持HTML解析,则为false。

+ +

在JSFiddle中查看

+ +

字符编码

+ +

如果在HTTP Content-Type 头部中声明了字符编码,则使用该字符编码。否则,如果存在字节顺序标记,则使用由字节顺序标记指示的编码。否则,如果有一个meta tag声明文件的前1024个字节中的编码,则使用该编码。否则,文件被解码为UTF-8。

+ +

老版本的浏览器中处理HTML

+ +

XMLHttpRequest最初只支持XML解析。 HTML解析支持是最近的一个补充。对于较老的浏览器,您甚至可以使用与正则表达式关联的responseText属性,以获取例如已知其ID的HTML元素的源代码:

+ +
function getHTML (oXHR, sTargetId) {
+  var  rOpen = new RegExp("<(?!\!)\\s*([^\\s>]+)[^>]*\\s+id\\=[\"\']" + sTargetId + "[\"\'][^>]*>" ,"i"),
+       sSrc = oXHR.responseText, aExec = rOpen.exec(sSrc);
+
+  return aExec ? (new RegExp("(?:(?:.(?!<\\s*" + aExec[1] + "[^>]*[>]))*.?<\\s*" + aExec[1] + "[^>]*[>](?:.(?!<\\s*\/\\s*" + aExec[1] + "\\s*>))*.?<\\s*\/\\s*" + aExec[1] + "\\s*>)*(?:.(?!<\\s*\/\\s*" + aExec[1] + "\\s*>))*.?", "i")).exec(sSrc.slice(sSrc.indexOf(aExec[0]) + aExec[0].length)) || "" : "";
+}
+
+var oReq = new XMLHttpRequest();
+oReq.open("GET", "yourPage.html", true);
+oReq.onload = function () { console.log(getHTML(this, "intro")); };
+oReq.send(null);
+
+ +
注: 该解决方案对于解释器来说更为昂贵. 仅在确实需要的情况下使用.
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Support18{{CompatGeckoDesktop("11.0")}}10{{CompatUnknown}}{{CompatNo}}
+ {{CompatVersionUnknown}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Support{{CompatUnknown}}{{CompatGeckoMobile("11.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] This feature was implemented in {{WebKitBug("74626")}}.

diff --git a/files/zh-cn/web/api/xmlhttprequest/index.html b/files/zh-cn/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..4498cb514e --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/index.html @@ -0,0 +1,192 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - API + - HTTP + - Reference + - Web + - XHR + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +
{{DefaultAPISidebar("XMLHttpRequest")}}
+ +

XMLHttpRequest(XHR)对象用于与服务器交互。通过 XMLHttpRequest 可以在不刷新页面的情况下请求特定 URL,获取数据。这允许网页在不影响用户操作的情况下,更新页面的局部内容。XMLHttpRequest 在 {{Glossary("AJAX")}} 编程中被大量使用。

+ +

{{InheritanceDiagram(650, 150)}}

+ +

尽管名称如此,XMLHttpRequest 可以用于获取任何类型的数据,而不仅仅是 XML。它甚至支持 HTTP 以外的协议(包括 file:// 和 FTP),尽管可能受到更多出于安全等原因的限制。

+ +

如果您的通信流程需要从服务器端接收事件或消息数据,请考虑通过 {{domxref("EventSource")}} 接口使用 server-sent events。对于全双工的通信, WebSocket 可能是更好的选择。

+ +

构造函数

+ +
+
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
+
该构造函数用于初始化一个 XMLHttpRequest 实例对象。在调用下列任何其他方法之前,必须先调用该构造函数,或通过其他方式,得到一个实例对象。
+
+ +

属性

+ +

此接口继承了 {{domxref("XMLHttpRequestEventTarget")}} 和 {{domxref("EventTarget")}} 的属性。

+ +
+
{{domxref("XMLHttpRequest.onreadystatechange")}}
+
readyState 属性发生变化时,调用的 {{domxref("EventHandler")}}。
+
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
+
返回 一个无符号短整型(unsigned short)数字,代表请求的状态码。
+
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
+
返回一个 {{domxref("ArrayBuffer")}}、{{domxref("Blob")}}、{{domxref("Document")}},或 {{domxref("DOMString")}},具体是哪种类型取决于 {{domxref("XMLHttpRequest.responseType")}} 的值。其中包含整个响应实体(response entity body)。
+
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
+
返回一个 {{domxref("DOMString")}},该 {{domxref("DOMString")}} 包含对请求的响应,如果请求未成功或尚未发送,则返回 null
+
{{domxref("XMLHttpRequest.responseType")}}
+
一个用于定义响应类型的枚举值(enumerated value)。
+
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
+
返回经过序列化(serialized)的响应 URL,如果该 URL 为空,则返回空字符串。
+
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
+
返回一个 {{domxref("Document")}},其中包含该请求的响应,如果请求未成功、尚未发送或时不能被解析为 XML 或 HTML,则返回 null
+
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
+
返回一个无符号短整型(unsigned short)数字,代表请求的响应状态。
+
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
+
返回一个 {{domxref("DOMString")}},其中包含 HTTP 服务器返回的响应状态。与 {{domxref("XMLHTTPRequest.status")}} 不同的是,它包含完整的响应状态文本(例如,"200 OK")。 +
+

注意:根据 HTTP/2 规范(8.1.2.4 Response Pseudo-Header Fields,响应伪标头字段),HTTP/2 没有定义任何用于携带 HTTP/1.1 状态行中包含的版本(version)或者原因短语(reason phrase)的方法。

+
+
+
+ +
+
{{domxref("XMLHttpRequest.timeout")}}
+
一个无符号长整型(unsigned long)数字,表示该请求的最大请求时间(毫秒),若超出该时间,请求会自动终止。
+
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
+
当请求超时调用的 {{domxref("EventHandler")}}。{{ gecko_minversion_inline(" 12.0 ")}}
+
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
+
{{domxref("XMLHttpRequestUpload")}},代表上传进度。
+
{{domxref("XMLHttpRequest.withCredentials")}}
+
一个{{domxref("Boolean", "布尔值")}},用来指定跨域 Access-Control 请求是否应当带有授权信息,如 cookie 或授权 header 头。
+
+ +

非标准属性

+ +
+
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
+
一个 {{Interface("nsIChannel")}},对象在执行请求时使用的通道。
+
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
+
一个布尔值,如果为真,请求将在没有 cookie 和身份验证 header 头的情况下发送。
+
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
+
一个布尔值,如果为真,则在请求时不会强制执行同源策略。
+
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
+
一个布尔值,它指示对象是否是后台服务器端的请求。
+
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
+
一个 {{jsxref("ArrayBuffer")}},把请求的响应作为一个 JavaScript TypedArray。
+
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
+
这是一个 Gecko 专有属性,是一个布尔值,已在 Firefox/Gecko 22 中被删除。请考虑使用 Server-Sent EventWeb Socket、或来自进度事件的 responseText 代替。
+
+ +

事件处理器

+ +

作为 XMLHttpRequest 实例的属性之一,所有浏览器都支持 onreadystatechange

+ +

后来,许多浏览器实现了一些额外的事件(onloadonerroronprogress 等)。详见Using XMLHttpRequest

+ +

更多现代浏览器,包括 Firefox,除了可以设置 on* 属性外,也提供标准的监听器 {{domxref("EventTarget.addEventListener", "addEventListener()")}} API 来监听XMLHttpRequest 事件。

+ +

方法

+ +
+
{{domxref("XMLHttpRequest.abort()")}}
+
如果请求已被发出,则立刻中止请求。
+
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
+
以字符串的形式返回所有用 {{Glossary("CRLF")}} 分隔的响应头,如果没有收到响应,则返回 null
+
{{domxref("XMLHttpRequest.getResponseHeader()")}}
+
返回包含指定响应头的字符串,如果响应尚未收到或响应中不存在该报头,则返回 null
+
{{domxref("XMLHttpRequest.open()")}}
+
初始化一个请求。该方法只能在 JavaScript 代码中使用,若要在 native code 中初始化请求,请使用 openRequest()
+
{{domxref("XMLHttpRequest.overrideMimeType()")}}
+
覆写由服务器返回的 MIME 类型。
+
{{domxref("XMLHttpRequest.send()")}}
+
发送请求。如果请求是异步的(默认),那么该方法将在请求发送后立即返回。
+
{{domxref("XMLHttpRequest.setRequestHeader()")}}
+
设置 HTTP 请求头的值。必须在 open() 之后、send() 之前调用 setRequestHeader() 方法。
+
+ +

非标准方法

+ +
+
{{domxref("XMLHttpRequest.init()")}}
+
在 C++ 代码中初始化一个 XHR 对象。 +
警告:该方法不能在 JavaScript 代码中使用。
+
+
{{domxref("XMLHttpRequest.openRequest()")}}
+
初始化一个请求。这个方法只能在原生 C++ 代码中使用;如果用 JavaScript 代码来初始化请求,使用 open() 代替。可参考 open() 的文档。
+
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
+
send() 方法的变体,用来发送二进制数据。
+
+ +

事件

+ +
+
{{domxref("XMLHttpRequest/abort_event", "abort")}}
+
当 request 被停止时触发,例如当程序调用 {{domxref("XMLHttpRequest.abort()")}} 时。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onabort", "onabort")}} 属性。
+
{{domxref("XMLHttpRequest/error_event", "error")}}
+
当 request 遭遇错误时触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onerror", "onerror")}} 属性
+
{{domxref("XMLHttpRequest/load_event", "load")}}
+
{{domxref("XMLHttpRequest")}}请求成功完成时触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onload", "onload")}} 属性.
+
{{domxref("XMLHttpRequest/loadend_event", "loadend")}}
+
当请求结束时触发, 无论请求成功 ( {{domxref("XMLHttpRequest/load_event", "load")}}) 还是失败 ({{domxref("XMLHttpRequest/abort_event", "abort")}} 或 {{domxref("XMLHttpRequest/error_event", "error")}})。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onloadend", "onloadend")}} 属性。
+
{{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}
+
接收到响应数据时触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onloadstart", "onloadstart")}} 属性。
+
{{domxref("XMLHttpRequest/progress_event", "progress")}}
+
当请求接收到更多数据时,周期性地触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/onprogress", "onprogress")}} 属性。
+
{{domxref("XMLHttpRequest/timeout_event", "timeout")}}
+
在预设时间内没有接收到响应时触发。
+ 也可以使用 {{domxref("XMLHttpRequestEventTarget/ontimeout", "ontimeout")}} 属性。
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

浏览器兼容性

+ + + +
{{Compat("api.XMLHttpRequest")}}
+ +

参见

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/load_event/index.html b/files/zh-cn/web/api/xmlhttprequest/load_event/index.html new file mode 100644 index 0000000000..47d3470174 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/load_event/index.html @@ -0,0 +1,142 @@ +--- +title: 'XMLHttpRequest: load event' +slug: Web/API/XMLHttpRequest/load_event +tags: + - XMLHttpRequest + - 接口 +translation_of: Web/API/XMLHttpRequest/load_event +--- +
{{APIRef}}
+ +

当一个{{domxref("XMLHttpRequest")}}请求完成的时候会触发load 事件。

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("ProgressEvent")}}
Event handler property{{domxref("XMLHttpRequestEventTarget/onload", "onload")}}
+ +

示例

+ +

在线例子

+ +

HTML

+ +
<div class="controls">
+    <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" />
+    <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" />
+    <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" />
+</div>
+
+<textarea readonly class="event-log"></textarea>
+ + + +

JS

+ +
const xhrButtonSuccess = document.querySelector('.xhr.success');
+const xhrButtonError = document.querySelector('.xhr.error');
+const xhrButtonAbort = document.querySelector('.xhr.abort');
+const log = document.querySelector('.event-log');
+
+function handleEvent(e) {
+    log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`;
+}
+
+function addListeners(xhr) {
+    xhr.addEventListener('loadstart', handleEvent);
+    xhr.addEventListener('load', handleEvent);
+    xhr.addEventListener('loadend', handleEvent);
+    xhr.addEventListener('progress', handleEvent);
+    xhr.addEventListener('error', handleEvent);
+    xhr.addEventListener('abort', handleEvent);
+}
+
+function runXHR(url) {
+    log.textContent = '';
+
+    const xhr = new XMLHttpRequest();
+    addListeners(xhr);
+    xhr.open("GET", url);
+    xhr.send();
+    return xhr;
+}
+
+xhrButtonSuccess.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg');
+});
+
+xhrButtonError.addEventListener('click', () => {
+    runXHR('https://somewhere.org/i-dont-exist');
+});
+
+xhrButtonAbort.addEventListener('click', () => {
+    runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort();
+});
+ +

结果

+ +

{{ EmbedLiveSample('Live_example', '100%', '150px') }}

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('XMLHttpRequest', '#event-xhr-load')}}{{Spec2('XMLHttpRequest')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.load_event")}}

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/mozanon/index.html b/files/zh-cn/web/api/xmlhttprequest/mozanon/index.html new file mode 100644 index 0000000000..82a447bf52 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/mozanon/index.html @@ -0,0 +1,16 @@ +--- +title: XMLHttpRequest.mozAnon +slug: Web/API/XMLHttpRequest/mozAnon +tags: + - API + - Authentication + - Cookies + - Non-standard + - Property + - XMLHttpRequest + - mozAnon +translation_of: Web/API/XMLHttpRequest/mozAnon +--- +
{{draft}}{{APIRef('XMLHttpRequest')}}
+ +

XMLHttpRequest.mozAnon 是布尔类型。如果这个变量为真,则这次请求将不携带cookies或头部认证信息来发送。

diff --git a/files/zh-cn/web/api/xmlhttprequest/mozbackgroundrequest/index.html b/files/zh-cn/web/api/xmlhttprequest/mozbackgroundrequest/index.html new file mode 100644 index 0000000000..f50d7fa2f3 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/mozbackgroundrequest/index.html @@ -0,0 +1,18 @@ +--- +title: XMLHttpRequest.mozBackgroundRequest +slug: Web/API/XMLHttpRequest/mozBackgroundRequest +translation_of: Web/API/XMLHttpRequest/mozBackgroundRequest +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +
+

Note: Web内容无法使用此方法。 它需要提升权限才能访问。

+
+ +

XMLHttpRequest.mozBackgroundRequest是一个布尔对象,表示object是否为后台的服务请求。 如果为true,则不会将任何加载组与请求关联,并且不会向用户显示安全对话框。

+ +

请求失败时通常会显示安全对话框(例如身份验证或错误证书通知)。

+ +
+

Note: 该属性必须在调用open()之前设置。

+
diff --git a/files/zh-cn/web/api/xmlhttprequest/mozresponsearraybuffer/index.html b/files/zh-cn/web/api/xmlhttprequest/mozresponsearraybuffer/index.html new file mode 100644 index 0000000000..108cb417b2 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/mozresponsearraybuffer/index.html @@ -0,0 +1,12 @@ +--- +title: XMLHttpRequest.mozResponseArrayBuffer +slug: Web/API/XMLHttpRequest/mozResponseArrayBuffer +translation_of: Web/API/XMLHttpRequest/mozResponseArrayBuffer +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +
+

自Gecko 6以来已过时

+
+ +

这是一个ArrayBuffer响应给这个请求,写为JavaScript类型数组。 如果请求不成功,或者它尚未发送,它就是NULL

diff --git a/files/zh-cn/web/api/xmlhttprequest/mozsystem/index.html b/files/zh-cn/web/api/xmlhttprequest/mozsystem/index.html new file mode 100644 index 0000000000..7e952fcfa9 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/mozsystem/index.html @@ -0,0 +1,10 @@ +--- +title: XMLHttpRequest.mozSystem +slug: Web/API/XMLHttpRequest/mozSystem +translation_of: Web/API/XMLHttpRequest/mozSystem +--- +
{{draft}}{{APIRef('XMLHttpRequest')}}
+ +

mozSystem is a boolean. If true, the same origin policy is not enforced on the request.

+ +

mozSystem 是一个布尔值。如果它被设置为true,那么在请求时就不会强制要求执行同源策略(Same Origin Policy)。

diff --git a/files/zh-cn/web/api/xmlhttprequest/onreadystatechange/index.html b/files/zh-cn/web/api/xmlhttprequest/onreadystatechange/index.html new file mode 100644 index 0000000000..76bd8c6ccf --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/onreadystatechange/index.html @@ -0,0 +1,120 @@ +--- +title: XMLHttpRequest.onreadystatechange +slug: Web/API/XMLHttpRequest/onreadystatechange +tags: + - XHR + - XMLHttpRequest + - 参考 + - 处理程序 + - 属性 + - 接口 +translation_of: Web/API/XMLHttpRequest/onreadystatechange +--- +
{{APIRef}}
+ +

只要 readyState 属性发生变化,就会调用相应的处理函数这个回调函数会被用户线程所调用。XMLHttpRequest.onreadystatechange 会在 {{domxref("XMLHttpRequest")}} 的{{domxref("XMLHttpRequest.readyState", "readyState")}} 属性发生改变时触发 {{event("readystatechange")}} 事件的时候被调用。

+ +
+

警告:这个方法不该用于同步的requests对象,并且不能在内部(C++)代码中使用.

+
+ +

当一个 XMLHttpRequest 请求被 abort() 方法取消时,其对应的 readystatechange 事件不会被触发。

+ +
+

UPDATE: 在下面的浏览器版本中会触发 (Firefox 51.0.1, Opera 43.0.2442.991, Safari 10.0.3 (12602.4.8), Chrome 54.0.2840.71, Edge, IE11). 例子在 here - 重新加载几次页面即可。

+
+ +

语法

+ +
XMLHttpRequest.onreadystatechange = callback;
+ +

取值

+ + + +

示例

+ +
var xhr= new XMLHttpRequest(),
+    method = "GET",
+    url = "https://developer.mozilla.org/";
+
+xhr.open(method, url, true);
+xhr.onreadystatechange = function () {
+  if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
+    console.log(xhr.responseText)
+  }
+}
+xhr.send();
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#handler-xhr-onreadystatechange')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1)}}{{CompatGeckoDesktop(1.0)}}{{CompatIe(7)}}[1]{{CompatVersionUnknown}}{{CompatSafari(1.2)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] IE 5 和 6可以通过使用 ActiveXObject() 支持ajax。

diff --git a/files/zh-cn/web/api/xmlhttprequest/open/index.html b/files/zh-cn/web/api/xmlhttprequest/open/index.html new file mode 100644 index 0000000000..431c77fb89 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/open/index.html @@ -0,0 +1,114 @@ +--- +title: XMLHttpRequest.open() +slug: Web/API/XMLHttpRequest/open +tags: + - Reference + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/open +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.open() 方法初始化一个请求。该方法要从JavaScript代码使用;从原生代码初始化一个请求,使用openRequest()替代。

+ +
注意:为已激活的请求调用此方法(open()openRequest()已被调用)相当于调用abort()
+ +

语法

+ +
xhrReq.open(method, url);
+xhrReq.open(method, url, async);
+xhrReq.open(method, url, async, user);
+xhrReq.open(method, url, async, user, password);
+
+ +

参数

+ +
+
method
+
要使用的HTTP方法,比如「GET」、「POST」、「PUT」、「DELETE」、等。对于非HTTP(S) URL被忽略。
+
url
+
一个{{domxref("DOMString")}}表示要向其发送请求的URL。
+
async {{optional_inline}}
+
一个可选的布尔参数,表示是否异步执行操作,默认为true。如果值为falsesend()方法直到收到答复前不会返回。如果true,已完成事务的通知可供事件监听器使用。如果multipart属性为true则这个必须为true,否则将引发异常。 +
注意:主线程上的同步请求很容易破坏用户体验,应该避免;实际上,许多浏览器已完全弃用主线程上的同步XHR支持。在 {{domxref("Worker")}}中允许同步请求
+
+
user {{optional_inline}}
+
可选的用户名用于认证用途;默认为null
+
password {{optional_inline}}
+
可选的密码用于认证用途,默认为null
+
+ +

规格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-open()-method', 'open()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(1)}}{{ CompatVersionUnknown}}{{CompatIe('5')}}[1]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown}}1.0{{CompatVersionUnknown}}{{ CompatVersionUnknown}}{{ CompatVersionUnknown}}{{ CompatVersionUnknown}}
+
+ +

[1] 该特性通过ActiveXObject()实现。Internet Explorer从7开始实现了标准的XMLHttpRequest。

+ +

参见

+ +

使用 XMLHttpRequest

diff --git a/files/zh-cn/web/api/xmlhttprequest/openrequest/index.html b/files/zh-cn/web/api/xmlhttprequest/openrequest/index.html new file mode 100644 index 0000000000..2fdd0ec2a3 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/openrequest/index.html @@ -0,0 +1,8 @@ +--- +title: XMLHttpRequest.openRequest() +slug: Web/API/XMLHttpRequest/openRequest +translation_of: Web/API/XMLHttpRequest/openRequest +--- +

{{APIRef("XMLHttpRequest")}}{{non-standard_header}}

+ +

此Mozilla特定的方法仅在特权代码中可用, 且仅能从C++上下文中调用以初始化 XMLHttpRequest.若想要从JavaScript代码初始化一个request,请使用标准的 {{domxref("XMLHttpRequest.open", "open()")}} 方法.

diff --git a/files/zh-cn/web/api/xmlhttprequest/overridemimetype/index.html b/files/zh-cn/web/api/xmlhttprequest/overridemimetype/index.html new file mode 100644 index 0000000000..1a13943abf --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/overridemimetype/index.html @@ -0,0 +1,68 @@ +--- +title: XMLHttpRequest.overrideMimeType() +slug: Web/API/XMLHttpRequest/overrideMimeType +translation_of: Web/API/XMLHttpRequest/overrideMimeType +--- +
XMLHttpRequest 的 overrideMimeType 方法是指定一个MIME类型用于替代服务器指定的类型,使服务端响应信息中传输的数据按照该指定MIME类型处理。例如强制使流方式处理为"text/xml"类型处理时会被使用到,即使服务器在响应头中并没有这样指定。此方法必须在send方法之前调用方为有效。
+ +

Syntax

+ +
XMLHttpRequest.overrideMimeType(mimeType)
+ +

Parameters

+ +
+
mimeType
+
一个 {{domxref("DOMString")}} 指定具体的MIME类型去代替有服务器指定的MIME类型. 如果服务器没有指定类型,那么 XMLHttpRequest 将会默认为 "text/xml".
+
+ +

Return value

+ +

undefined.

+ +

Example

+ +

这个样例指定Content-Type为“text/plain",为接受的数据重写ContentType

+ +
+

Note:  如果服务器没有指定一个Content-Type 头, {{domxref("XMLHttpRequest")}} 默认MIME类型为"text/xml". 如果接受的数据不是有效的XML,将会出现格”格式不正确“的错误。你能够通过调用 overrideMimeType() 指定各种类型来避免这种情况。

+
+ +
// Interpret the received data as plain text
+
+req = new XMLHttpRequest();
+req.overrideMimeType("text/plain");
+req.addEventListener("load", callback, false);
+req.open("get", url);
+req.send();
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-overrideMimeType()-method', 'overrideMimeType()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Browser compatibility

+ + + +

{{Compat("api.XMLHttpRequest.overrideMimeType")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/readystate/index.html b/files/zh-cn/web/api/xmlhttprequest/readystate/index.html new file mode 100644 index 0000000000..c47030c9c8 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/readystate/index.html @@ -0,0 +1,109 @@ +--- +title: XMLHttpRequest.readyState +slug: Web/API/XMLHttpRequest/readyState +tags: + - AJAX + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/readyState +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.readyState 属性返回一个 XMLHttpRequest  代理当前所处的状态。一个 XHR 代理总是处于下列状态中的一个:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
状态描述
0UNSENT代理被创建,但尚未调用 open() 方法。
1OPENEDopen() 方法已经被调用。
2HEADERS_RECEIVEDsend() 方法已经被调用,并且头部和状态已经可获得。
3LOADING下载中; responseText 属性已经包含部分数据。
4DONE下载操作已完成。
+ +
+
UNSENT
+
XMLHttpRequest 代理已被创建, 但尚未调用 open() 方法。
+
OPENED
+
open() 方法已经被触发。在这个状态中,可以通过  setRequestHeader() 方法来设置请求的头部, 可以调用 send() 方法来发起请求。
+
HEADERS_RECEIVED
+
send() 方法已经被调用,响应头也已经被接收。
+
LOADING
+
响应体部分正在被接收。如果 responseType 属性是“text”或空字符串, responseText 将会在载入的过程中拥有部分响应数据。
+
DONE
+
请求操作已经完成。这意味着数据传输已经彻底完成或失败。
+
+ +
+

在IE中,状态有着不同的名称,并不是 UNSENTOPENEDHEADERS_RECEIVEDLOADING 和 DONE, 而是 READYSTATE_UNINITIALIZED (0),READYSTATE_LOADING (1) , READYSTATE_LOADED (2) , READYSTATE_INTERACTIVE (3) 和 READYSTATE_COMPLETE (4) 。

+
+ +

示例

+ +
var xhr = new XMLHttpRequest();
+console.log('UNSENT', xhr.readyState); // readyState 为 0
+
+xhr.open('GET', '/api', true);
+console.log('OPENED', xhr.readyState); // readyState 为 1
+
+xhr.onprogress = function () {
+    console.log('LOADING', xhr.readyState); // readyState 为 3
+};
+
+xhr.onload = function () {
+    console.log('DONE', xhr.readyState); // readyState 为 4
+};
+
+xhr.send(null);
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#states')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.readyState")}}

+ +
 
diff --git a/files/zh-cn/web/api/xmlhttprequest/response/index.html b/files/zh-cn/web/api/xmlhttprequest/response/index.html new file mode 100644 index 0000000000..71ecacaa8c --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/response/index.html @@ -0,0 +1,93 @@ +--- +title: XMLHttpRequest.response +slug: Web/API/XMLHttpRequest/response +tags: + - AJAX + - API + - XHR + - XMLHttpRequest + - 加载数据 + - 参考 + - 只读 + - 响应 + - 属性 + - 服务器 + - 获取内容 + - 获取数据 + - 读取数据 +translation_of: Web/API/XMLHttpRequest/response +--- +
{{APIRef('XMLHttpRequest')}}
+ +

{{domxref("XMLHttpRequest")}} response 属性返回响应的正文。返回的类型为 {{domxref("ArrayBuffer")}} 、 {{domxref("Blob")}} 、 {{domxref("Document")}} 、 JavaScript {{jsxref("Object")}} 或 {{domxref("DOMString")}} 中的一个。 这取决于 {{domxref("XMLHttpRequest.responseType", "responseType")}} 属性。

+ +

语法

+ +
var body = XMLHttpRequest.response;
+
+ +

取值

+ +

一个对象,其类型取决于 {{domxref("XMLHttpRequest.responseType", "responseType")}} 的值。你可以尝试设置 responseType 的值,以便通过特定的类型请求数据。 responseType 要在调用 {{domxref("XMLHttpRequest.open", "open()")}} 初始化请求之后调用,并且要在调用 {{domxref("XMLHttpRequest.send", "send()")}} 发送请求到服务器之前调用。

+ +

如果请求尚未完成或未成功,则取值是 null 。例外的,读取文本数据时如果将 responseType 的值设置成"text"或空字符串("")且当请求状态还在是 LOADING {{domxref("XMLHttpRequest.readyState", "readyState")}} (3) 时,response 包含到目前为止该请求已经取得的内容。

+ +

响应的类型如下所示。

+ +

{{page("/zh-CN/docs/Web/API/XMLHttpRequestResponseType", "取值")}}

+ +
+
+ +

例子

+ +

此例子提供了一个方法—— load() ,它可以从服务器加载和处理页面。它通过创建一个 {{domxref("XMLHttpRequest")}} 对象并为 {{event("readystatechange")}} 事件创建一个监听器。这样的话,当 readyState 变成 DONE (4) 时就会获取 response 并将其传递给 load() 中提供的回调函数。

+ +

返回的内容会被作为原始文本数据处理 (因为这里没有覆盖  {{domxref("XMLHttpRequest.responseType", "responseType")}} 的默认值)。

+ +
var url = 'somePage.html'; //一个本地页面
+
+function load(url, callback) {
+  var xhr = new XMLHttpRequest();
+
+  xhr.onreadystatechange = function() {
+    if (xhr.readyState === 4) {
+      callback(xhr.response);
+    }
+  }
+
+  xhr.open('GET', url, true);
+  xhr.send('');
+}
+
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-response-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.response")}}

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/responsetext/index.html b/files/zh-cn/web/api/xmlhttprequest/responsetext/index.html new file mode 100644 index 0000000000..5b6708acd4 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/responsetext/index.html @@ -0,0 +1,114 @@ +--- +title: XMLHttpRequest.responseText +slug: Web/API/XMLHttpRequest/responseText +tags: + - XMLHttpRequest.responseText +translation_of: Web/API/XMLHttpRequest/responseText +--- +
{{draft}}
+ +
{{APIRef('XMLHttpRequest')}}
+ +

XMLHttpRequest.responseText 在一个请求被发送后,从服务器端返回文本。

+ +

语法

+ +
var resultText = XMLHttpRequest.responseText;
+ +

取值

+ +

{{domxref("DOMString")}} 是XMLHttpRequest 返回的纯文本的值。当{{domxref("DOMString")}} 为null时,表示请求失败了。当{{domxref("DOMString")}} 为""时,表示这个请求还没有被{{domxref("XMLHttpRequest.send", "send()")}}

+ +

当处理一个异步request的时候,尽管当前请求并没有结束,responseText的返回值是当前从后端收到的内容。

+ +

当请求状态{{domxref("XMLHttpRequest.readyState", "readyState")}}变为{{domxref("XMLHttpRequest.DONE", "XMLHttpRequest.DONE")}} (4),且{{domxref("XMLHttpRequest.status", "status")}}值为200("OK")时,responseText是全部后端的返回数据

+ +

例子

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+// If specified, responseType must be empty string or "text"
+xhr.responseType = 'text';
+
+xhr.onload = function () {
+    if (xhr.readyState === xhr.DONE) {
+        if (xhr.status === 200) {
+            console.log(xhr.response);
+            console.log(xhr.responseText);
+        }
+    }
+};
+
+xhr.send(null);
+ +

格式

+ + + + + + + + + + + + + + +
格式状态备注
{{SpecName('XMLHttpRequest', '#the-responsetext-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 在IE10前的版本请求完成时, XMLHttpRequest.responseText 的值为只读。

diff --git a/files/zh-cn/web/api/xmlhttprequest/responsetype/index.html b/files/zh-cn/web/api/xmlhttprequest/responsetype/index.html new file mode 100644 index 0000000000..28233b4c48 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/responsetype/index.html @@ -0,0 +1,47 @@ +--- +title: XMLHttpRequest.responseType +slug: Web/API/XMLHttpRequest/responseType +tags: + - XMLHttpRequest.responseType +translation_of: Web/API/XMLHttpRequest/responseType +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.responseType 属性是一个枚举类型的属性,返回响应数据的类型。它允许我们手动的设置返回数据的类型。如果我们将它设置为一个空字符串,它将使用默认的"text"类型。

+ +

在工作环境(Work Environment)中将responseType的值设置为"document"通常会被忽略. 当将responseType设置为一个特定的类型时,你需要确保服务器所返回的类型和你所设置的返回值类型是兼容的。那么如果两者类型不兼容呢?恭喜你,你会发现服务器返回的数据变成了null,即使服务器返回了数据。还有一个要注意的是,给一个同步请求设置responseType会抛出一个InvalidAccessError 的异常。

+ +

responseType支持以下几种值:

+ +

{{page("/zh-CN/docs/Web/API/XMLHttpRequestResponseType", "取值")}}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-responsetype-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.responseType")}}

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/responseurl/index.html b/files/zh-cn/web/api/xmlhttprequest/responseurl/index.html new file mode 100644 index 0000000000..4e70133f8b --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/responseurl/index.html @@ -0,0 +1,90 @@ +--- +title: XMLHttpRequest.responseURL +slug: Web/API/XMLHttpRequest/responseURL +tags: + - XMLHttpRequest.responseURL +translation_of: Web/API/XMLHttpRequest/responseURL +--- +

{{APIRef('XMLHttpRequest')}}

+ +

只读属性XMLHttpRequest.responseURL返回响应的序列化URL,如果URL为空则返回空字符串。如果URL有锚点,则位于URL # 后面的内容会被删除。如果URL有重定向, responseURL 的值会是经过多次重定向后的最终 URL 。

+ +

实例

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', 'http://example.com/test', true);
+xhr.onload = function () {
+  console.log(xhr.responseURL); // http://example.com/test
+};
+xhr.send(null);
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-responseurl-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(37.0)}}{{CompatGeckoDesktop("32.0")}}{{CompatNo}}{{CompatOpera("24")}}{{CompatSafari(8.0)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

 

diff --git a/files/zh-cn/web/api/xmlhttprequest/responsexml/index.html b/files/zh-cn/web/api/xmlhttprequest/responsexml/index.html new file mode 100644 index 0000000000..ffd22d7896 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/responsexml/index.html @@ -0,0 +1,135 @@ +--- +title: XMLHttpRequest.responseXML +slug: Web/API/XMLHttpRequest/responseXML +tags: + - XMLHttpRequest.responseXML +translation_of: Web/API/XMLHttpRequest/responseXML +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.responseXML 属性是一个只读值,它返回一个包含请求检索的HTML或XML的{{domxref("Document")}},如果请求未成功,尚未发送,或者检索的数据无法正确解析为 XML 或 HTML,则为 null。默认是当作“text / xml” 来解析。当 {{domxref("XMLHttpRequest.responseType", "responseType")}} 设置为 “document” 并且请求已异步执行时,响应将被当作 “text / html” 来解析。responseXML 对于任何其他类型的数据以及 data: URLs 为 null。

+ +
+

responseXML 在这个属性的历史堪称神器,它可以同时在 HTML 和 XML 中工作

+
+ +

如果服务器没有明确指出 {{HTTPHeader("Content-Type")}} 头是 "text/xml" 还是 "application/xml", 你可以使用{{domxref("XMLHttpRequest.overrideMimeType()")}} 强制 XMLHttpRequest 解析为 XML.

+ +

语法

+ +
var data = XMLHttpRequest.responseXML;
+
+ +

+ +

 {{domxref("Document")}} 中包含从 {{domxref("XMLHttpRequest")}} 中收到的 HTML 节点或解析后的 XML 节点,也可能是在没有收到任何数据或数据类型错误的情况下返回的 null.

+ +

例外

+ +
+
InvalidStateError
+
{{domxref("XMLHttpRequest.responseType", "responseType")}} 既不是 "document" 也不是空字符串 (接收的数据应是XML 或 HTML).
+
+ +

示例

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+// 如果已指明,responseType 必须是空字符串或 "document"
+xhr.responseType = 'document';
+
+// overrideMimeType() 用来强制解析 response 为 XML
+xhr.overrideMimeType('text/xml');
+
+xhr.onload = function () {
+  if (xhr.readyState === xhr.DONE) {
+    if (xhr.status === 200) {
+      console.log(xhr.response);
+      console.log(xhr.responseXML);
+    }
+  }
+};
+
+xhr.send(null);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-responsexml-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)[1]Microsoft EdgeInternet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] 在 Firefox 51 之前, 解析收到数据的错误会在 {{domxref("Document")}} 的顶部添加一个 <parsererror> 节点,并且在任何状态下返回 Document 。这是不符合规范的。从 Firefox 51开始,这种情况可以正确的返回 null。

+ +

了解更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/send/index.html b/files/zh-cn/web/api/xmlhttprequest/send/index.html new file mode 100644 index 0000000000..6b96c92ebd --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/send/index.html @@ -0,0 +1,261 @@ +--- +title: XMLHttpRequest.send() +slug: Web/API/XMLHttpRequest/send +tags: + - AJAX + - API + - HTTP request + - Method + - XHR + - XMLHttpRequest + - send +translation_of: Web/API/XMLHttpRequest/send +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.send() 方法用于发送 HTTP 请求。如果是异步请求(默认为异步请求),则此方法会在请求发送后立即返回;如果是同步请求,则此方法直到响应到达后才会返回。XMLHttpRequest.send() 方法接受一个可选的参数,其作为请求主体;如果请求方法是 GET 或者 HEAD,则应将请求主体设置为 null。

+ +

如果没有使用 {{domxref("XMLHttpRequest.setRequestHeader", "setRequestHeader()")}} 方法设置 {{HTTPHeader("Accept")}} 头部信息,则会发送带有 "* / *" 的{{HTTPHeader("Accept")}} 头部。

+ +
+

Note: 请注意不要使用一个简单的AarryBuffer对象作为参数,ArrayBuffer已经不再是ajax规范的一部分,请改用ArrayBufferView(有关信息请参考兼容性列表。)

+
+ +

语法

+ +
XMLHttpRequest.send(body)
+ +

参数

+ +
+
body {{optional_inline}}
+
在XHR请求中要发送的数据体. 可以是: +
    +
  • 可以为 {{domxref("Document")}}, 在这种情况下,它在发送之前被序列化.
  • +
  • 为 XMLHttpRequestBodyInit, 从 per the Fetch spec (规范中)可以是 {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, 或者 {{domxref("USVString")}} 对象.
  • +
  • null
  • +
+ 如果body没有指定值,则默认值为 null .
+
+

返回值

+ +

undefined.

+ +

 例外

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateErrorsend() has already been invoked for the request, and/or the request is complete.
NetworkErrorThe resource type to be fetched is a Blob, and the method is not GET.
+
+
+ +
XMLHttpRequest.send();
+XMLHttpRequest.send(ArrayBuffer data);
+XMLHttpRequest.send(ArrayBufferView data);
+XMLHttpRequest.send(Blob data);
+XMLHttpRequest.send(Document data);
+XMLHttpRequest.send(DOMString? data);
+XMLHttpRequest.send(FormData data);
+
+ +

如果发送的数据是Document对象,需要在发送之前将其序列化。当发送一个Document对象时,Firefox 3之前的版本都是使用utf-8编码发送请求的;FireFox 3则使用由body.xmlEncoding指定的编码格式正确的发送文档,但如果未指定编码格式,则使用utf-8编码格式发送。

+ +

如果是一个nsIInputStream接口,它必须与nsIUploadChannel的setUploadStream()方法兼容。在这种情况下,将 Content-Length的头部添加到请求中,它的值则使用nsIInputStream接口的available()方法获取。任何报头包括在数据流顶部的都会被当做报文主体。所以,应该在发送请求即调用send()方法之前使用setRequestHeader() 方法设置 Content-Type头部来指定数据流的MIME类型。

+ +

发送二进制内容的最佳方法(如上传文件)是使用一个与send()方法结合的 ArrayBufferView 或者Blobs

+ +

案例: GET

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+xhr.onload = function () {
+   // 请求结束后,在此处写处理代码
+};
+
+xhr.send(null);
+// xhr.send('string');
+// xhr.send(new Blob());
+// xhr.send(new Int8Array());
+// xhr.send({ form: 'data' });
+// xhr.send(document);
+
+ +

案例: POST

+ +
var xhr = new XMLHttpRequest();
+xhr.open("POST", '/server', true);
+
+//发送合适的请求头信息
+xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
+
+xhr.onload = function () {
+    // 请求结束后,在此处写处理代码
+};
+xhr.send("foo=bar&lorem=ipsum");
+// xhr.send('string');
+// xhr.send(new Blob());
+// xhr.send(new Int8Array());
+// xhr.send({ form: 'data' });
+// xhr.send(document);
+
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注解
{{SpecName('XMLHttpRequest', '#the-send()-method', 'send()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特点ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatChrome(1)}}{{CompatGeckoDesktop("1.0")}}{{CompatIe('5')}}[2]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
send(ArrayBuffer){{CompatChrome(9)}}{{CompatGeckoDesktop("9.0")}}[1]{{CompatIe('10')}}{{CompatOpera('11.60')}}{{compatUnknown}}
send(ArrayBufferView){{CompatChrome(22)}}{{CompatGeckoDesktop("20.0")}}{{compatUnknown}}{{compatUnknown}}{{compatUnknown}}
send(Blob){{CompatChrome(7)}}{{CompatGeckoDesktop("1.9.2")}}{{CompatIe('10')}}{{CompatOpera('12')}}{{compatUnknown}}
send(FormData){{CompatChrome(6)}}{{CompatGeckoDesktop("2.0")}}{{CompatIe('10')}}{{CompatOpera('12')}}{{compatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特点AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
send(ArrayBuffer){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{compatUnknown}}
send(ArrayBufferView){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{compatUnknown}}
send(Blob){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{compatUnknown}}
send(FormData){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{compatUnknown}}
+
+ +

[1] 发送一个简单的ArrayBuffer对象已不再是ajax规范一部分,也已经被弃用了。请使用 已被加入Gecko 20.0 {{geckoRelease("20.0")}}的ArrayBufferView

+ +

[2] 由于 Internet Explorer 7实现了标准的XMLHttpRequest,此功能通过ActiveXObject()实现。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/sending_and_receiving_binary_data/index.html b/files/zh-cn/web/api/xmlhttprequest/sending_and_receiving_binary_data/index.html new file mode 100644 index 0000000000..fc7da39cfd --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/sending_and_receiving_binary_data/index.html @@ -0,0 +1,153 @@ +--- +title: 发送和接收二进制数据 +slug: Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data +tags: + - AJAX + - FileReader + - MIME + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data +--- +

使用JavaScript类型数组接受二进制数据

+ +

可以通过设置一个XMLHttpRequest对象的 responseType属性来改变一个从服务器上返回的响应的数据类型.可用的属性值为空字符串 (默认), "arraybuffer", "blob", "document","json" 和 "text". response属性的值会根据responseType属性包含实体主体(entity body), 它可能会是一个 ArrayBuffer, Blob, Document,JSON, string,或者为NULL(如果请求未完成或失败)

+ +

下例读取了一个二进制图像文件,并且由该文件的二进制原生字节创建了一个8位无符号整数的数组.注意,这不会解码图像,但会读取像素。 你需要一个png解码库(png decoding library)。

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", "/myfile.png", true);
+oReq.responseType = "arraybuffer";
+
+oReq.onload = function (oEvent) {
+  var arrayBuffer = oReq.response; // 注意:不是oReq.responseText
+  if (arrayBuffer) {
+    var byteArray = new Uint8Array(arrayBuffer);
+    for (var i = 0; i < byteArray.byteLength; i++) {
+      // 对数组中的每个字节进行操作
+    }
+  }
+};
+
+oReq.send(null);
+
+ +

也可以通过给responseType属性设置为“blob”,将二进制文件读取为{{domxref("Blob")}}类型的数据。

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", "/myfile.png", true);
+oReq.responseType = "blob";
+
+oReq.onload = function(oEvent) {
+  var blob = oReq.response;
+  // ...
+};
+
+oReq.send();
+ +

在老的浏览器中接受二进制数据

+ +

下面的load_binary_resource()方法可以从指定的URL那里加载二进制数据,并将数据返回给调用者.

+ +
function load_binary_resource(url) {
+  var req = new XMLHttpRequest();
+  req.open('GET', url, false);
+  //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
+  req.overrideMimeType('text/plain; charset=x-user-defined');
+  req.send(null);
+  if (req.status != 200) return '';
+  return req.responseText;
+}
+
+ +

最为奇妙的操作在第五行,该行重写了默认的MIME类型,强制浏览器将该响应当成纯文本文件来对待, 使用一个用户自定义的字符集.这样就是告诉了浏览器,不要去解析数据,直接返回未处理过的字节码.

+ +
var filestream = load_binary_resource(url);
+var abyte = filestream.charCodeAt(x) & 0xff; // 扔掉的高位字节(f7)
+
+ +

上例从请求回来的二进制数据中得到偏移量为x处的字节.有效的偏移量范围是0到filestream.length-1.

+ +

查看 使用XMLHttpRequest下载文件 了解详情,查看下载文件.

+ +

发送二进制数据

+ +

XMLHttpRequest对象的send方法已被增强,可以通过简单的传入一个ArrayBuffer, {{ domxref("Blob") }}, 或者 {{ domxref("File") }}对象来发送二进制数据.

+ +

下例创建了一个文本文件,并使用POST方法将该文件发送到了服务器上.你也可以使用文本文件之外的其他二进制数据类型.

+ +
var oReq = new XMLHttpRequest();
+oReq.open("POST", url, true);
+oReq.onload = function (oEvent) {
+  // 上传完成后.
+};
+
+var bb = new BlobBuilder(); // 需要合适的前缀: window.MozBlobBuilder 或者 window.WebKitBlobBuilder
+bb.append('abc123');
+
+oReq.send(bb.getBlob('text/plain'));
+
+ +

将类型数组作为二进制数据发送

+ +

你可以将JavaScript类型数组作为二进制数据发送出去.

+ +
var myArray = new ArrayBuffer(512);
+var longInt8View = new Uint8Array(myArray);
+
+for (var i=0; i< longInt8View.length; i++) {
+  longInt8View[i] = i % 255;
+}
+
+var xhr = new XMLHttpRequest;
+xhr.open("POST", url, false);
+xhr.send(myArray);
+
+ +

上例新建了一个512字节的8比特整数的数组并发送它,当然,你也可以发送任意的二进制数据.

+ +
注意: 从Gecko 9.0 {{ geckoRelease("9.0") }}开始,添加了使用XMLHttpRequest发送 ArrayBuffer对象的功能.
+ +

提交表单和上传文件

+ +

请阅读此文

+ +

Firefox私有方法

+ +

下面的例子使用了POST请求,用Firefox私有的非标准方法sendAsBinary()将二进制数据以异步模式传输了出去.

+ +
var req = new XMLHttpRequest();
+req.open("POST", url, true);
+// 这里应该设置适当的MIME请求头
+req.setRequestHeader("Content-Length", 741);
+req.sendAsBinary(aBody);
+
+ +

第四行将Content-Length请求头设置为741,表示发送的数据长度为741个字节.你应该根据你要发送的数据的大小改变这个值.

+ +

第五行使用sendAsBinary()方法发送这个请求.

+ +

你也可以通过将一个{{ interface("nsIFileInputStream") }}对象实例传给send()方法来发送二进制内容,这样的话,你不需要自己去设置Content-Length请求头的大小,程序会自动设置:

+ +
// 新建一个文件流.
+var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
+                       .createInstance(Components.interfaces.nsIFileInputStream);
+stream.init(file, 0x04 | 0x08, 0644, 0x04); // file是一个nsIFile对象实例
+
+// 设置文件的MIME类型
+var mimeType = "text\/plain";
+try {
+  var mimeService = Components.classes["@mozilla.org/mime;1"]
+          .getService(Components.interfaces.nsIMIMEService);
+  mimeType = mimeService.getTypeFromFile(file); // file是一个nsIFile对象实例
+}
+catch (oEvent) { /* 丢弃异常,使用默认的text/plain类型 */ }
+
+// 发送
+var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
+                    .createInstance(Components.interfaces.nsIXMLHttpRequest);
+req.open('PUT', url, false); /* 同步模式! */
+req.setRequestHeader('Content-Type', mimeType);
+req.send(stream);
+
+ +

{{APIRef("XMLHttpRequest")}}

diff --git a/files/zh-cn/web/api/xmlhttprequest/setrequestheader/index.html b/files/zh-cn/web/api/xmlhttprequest/setrequestheader/index.html new file mode 100644 index 0000000000..2aaf964b5b --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/setrequestheader/index.html @@ -0,0 +1,109 @@ +--- +title: XMLHttpRequest.setRequestHeader() +slug: Web/API/XMLHttpRequest/setRequestHeader +tags: + - Reference + - XMLHttpRequests +translation_of: Web/API/XMLHttpRequest/setRequestHeader +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.setRequestHeader() 是设置HTTP请求头部的方法。此方法必须在  {{domxref("XMLHttpRequest.open", "open()")}} 方法和 {{domxref("XMLHttpRequest.send", "send()")}}   之间调用。如果多次对同一个请求头赋值,只会生成一个合并了多个值的请求头。

+ +

如果没有设置 {{HTTPHeader("Accept")}} 属性,则此发送出{{domxref("XMLHttpRequest.send", "send()")}} 的值为此属性的默认值*/* 。

+ +

安全起见,有些请求头的值只能由user agent设置:{{Glossary("Forbidden_header_name", "forbidden header names", 1)}}和{{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

+ +
+

自定义一些header属性进行跨域请求时,可能会遇到"not allowed by Access-Control-Allow-Headers in preflight response",你可能需要在你的服务端设置"Access-Control-Allow-Headers"。

+
+ +

语法

+ +
myReq.setRequestHeader(header, value);
+
+ +

参数

+ +
+
header
+
属性的名称。
+
value
+
属性的值。
+
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-setRequestHeader()-method', 'setRequestHeader()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(1)}}{{CompatUnknown}}{{CompatIe('5')}}[1]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 使用ActiveXObject()实现的。Internet Explorer 7之后使用的是标准的XMLHttpRequest。

+ +

参考

+ +

使用XMLHttpRequest

diff --git a/files/zh-cn/web/api/xmlhttprequest/status/index.html b/files/zh-cn/web/api/xmlhttprequest/status/index.html new file mode 100644 index 0000000000..d248bf2090 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/status/index.html @@ -0,0 +1,79 @@ +--- +title: XMLHttpRequest.status +slug: Web/API/XMLHttpRequest/status +tags: + - API + - Error + - Property + - Reference + - XMLHttpRequest + - XMLHttpRequest 状态 + - result + - status +translation_of: Web/API/XMLHttpRequest/status +--- +
{{APIRef('XMLHttpRequest')}}
+ +
只读属性 XMLHttpRequest.status 返回了XMLHttpRequest 响应中的数字状态码。status 的值是一个无符号短整型。在请求完成前,status的值为0。值得注意的是,如果 XMLHttpRequest 出错,浏览器返回的 status 也为0。
+ +
 
+ +
status码是标准的HTTP status codes。举个例子,status 200 代表一个成功的请求。如果服务器响应中没有明确指定status码,XMLHttpRequest.status 将会默认为200
+ +

例子

+ +
var xhr = new XMLHttpRequest();
+console.log('UNSENT', xhr.status);
+
+xhr.open('GET', '/server', true);
+console.log('OPENED', xhr.status);
+
+xhr.onprogress = function () {
+  console.log('LOADING', xhr.status);
+};
+
+xhr.onload = function () {
+  console.log('DONE', xhr.status);
+};
+
+xhr.send(null);
+
+/**
+ * 输出如下:
+ *
+ * UNSENT(未发送) 0
+ * OPENED(已打开) 0
+ * LOADING(载入中) 200
+ * DONE(完成) 200
+ */
+
+ +

标准

+ + + + + + + + + + + + + + +
标准状态备注
{{SpecName('XMLHttpRequest', '#the-status-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.status")}}

+ +

其他相关资料

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/statustext/index.html b/files/zh-cn/web/api/xmlhttprequest/statustext/index.html new file mode 100644 index 0000000000..7935aab46b --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/statustext/index.html @@ -0,0 +1,70 @@ +--- +title: XMLHttpRequest.statusText +slug: Web/API/XMLHttpRequest/statusText +translation_of: Web/API/XMLHttpRequest/statusText +--- +
{{APIRef('XMLHttpRequest')}}
+ +
只读属性 XMLHttpRequest.statusText 返回了XMLHttpRequest 请求中由服务器返回的一个DOMString 类型的文本信息,这则信息中也包含了响应的数字状态码。不同于使用一个数字来指示的状态码XMLHTTPRequest.status,这个属性包含了返回状态对应的文本信息,例如"OK"或是"Not Found"。如果请求的状态readyState的值为"UNSENT"或者"OPENED",则这个属性的值将会是一个空字符串。
+ +
+ +
如果服务器未明确指定一个状态文本信息,则statusText的值将会被自动赋值为"OK"。
+ +

例子

+ +
var xhr = new XMLHttpRequest();
+console.log('0 UNSENT', xhr.statusText);
+
+xhr.open('GET', '/server', true);
+console.log('1 OPENED', xhr.statusText);
+
+xhr.onprogress = function () {
+  console.log('3 LOADING', xhr.statusText);
+};
+
+xhr.onload = function () {
+  console.log('4 DONE', xhr.statusText);
+};
+
+xhr.send(null);
+
+/**
+ * 输出如下:
+ *
+ * 0 UNSENT
+ * 1 OPENED
+ * 3 LOADING OK
+ * 4 DONE OK
+ */
+
+ +

标准

+ + + + + + + + + + + + + + +
标准状态备注
{{SpecName('XMLHttpRequest', '#the-statustext-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest.statusText")}}

+ +

参考内容

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html b/files/zh-cn/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html new file mode 100644 index 0000000000..4da165b346 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html @@ -0,0 +1,237 @@ +--- +title: 同步和异步请求 +slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +tags: + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +--- +

XMLHttpRequest 支持同步和异步通信。但是,一般来说,出于性能原因,异步请求应优先于同步请求。

+ +

同步请求阻止代码的执行,这会导致屏幕上出现“冻结”和无响应的用户体验。

+ +

异步请求

+ +

如果你使用XMLHttpRequest发送异步请求,那么当请求的响应数据完全收到之时,会执行一个指定的回调函数,而在执行异步请求的同时,浏览器会正常地执行其他事务的处理。

+ +

例子:在控制台输出页面源文件

+ +

这个例子演示了如何进行一个简单的异步请求。

+ +
var xhr = new XMLHttpRequest();
+xhr.open("GET", "/bar/foo.txt", true);
+xhr.onload = function (e) {
+  if (xhr.readyState === 4) {
+    if (xhr.status === 200) {
+      console.log(xhr.responseText);
+    } else {
+      console.error(xhr.statusText);
+    }
+  }
+};
+xhr.onerror = function (e) {
+  console.error(xhr.statusText);
+};
+xhr.send(null);
+ +

第2行中指定第三个参数为true表示该请求应该以异步模式执行。

+ +

第3行创建一个事件处理函数对象,并将其分配给请求的onload属性。此处理程序查看请求的readyState,以查看事务是否在第4行完成,如果是,并且HTTP状态为200,则转储接收到的内容。如果发生错误,则显示错误消息。

+ +

第15行实际上启动了请求。只要请求的状态发生变化,就会调用回调程序。

+ +

例子:创建一个标准的方法来读取外部文件

+ +

在一些需求情况下,必须读取多个外部文件. 这是一个标准的函数. 该函数使用XMLHttpRequest对象进行异步请求.而且可以为每个文件读取完成后指定不同的回调函数.

+ +
function xhrSuccess() {
+    this.callback.apply(this, this.arguments);
+}
+
+function xhrError() {
+    console.error(this.statusText);
+}
+
+function loadFile(url, callback /*, opt_arg1, opt_arg2, ... */) {
+    var xhr = new XMLHttpRequest();
+    xhr.callback = callback;
+    xhr.arguments = Array.prototype.slice.call(arguments, 2);
+    xhr.onload = xhrSuccess;
+    xhr.onerror = xhrError;
+    xhr.open("GET", url, true);
+    xhr.send(null);
+}
+ +

用法:

+ +
function showMessage(message) {
+    console.log(message + this.responseText);
+}
+
+loadFile("message.txt", showMessage, "New message!\n\n");
+
+ +

实用函数loadFile的签名声明(i)要读取的目标URL(通过HTTP GET),(ii)成功完成XHR操作时执行的函数,以及(iii)任意列表的附加参数“通过“XHR对象到成功回调函数。

+ +

第1行声明XHR操作成功完成时调用的函数。它又调用已经分配给XHR对象(第7行)属性的loadFile函数(本例中为函数showMessage)的调用中指定的回调函数。提供给调用函数loadFile的附加参数(如果有的话)被“应用”到回调函数的运行中。

+ +

第5行声明XHR操作无法成功完成时调用的函数。

+ +

第7行存储XHR对象,成功回调函数作为loadFile的第二个参数给出。

+ +

第12行将参数赋给loadFile的调用。从第三个参数开始,收集所有剩余的参数,分配给变量xhr的arguments属性,传递给成功回调函数xhrSuccess,最终提供给函数调用的回调函数(在本例中为showMessage) xhrSuccess。

+ +

第15行为其第三个参数指定了true,表示该请求应该被异步处理。

+ +

第16行实际启动请求。

+ +

例子:使用超时

+ +

你可以使用一个超时设置,来避免你的代码为了等候读取请求的返回数据长时间执行.超时毫秒数可以通过为XMLHttpRequest对象的timeout 属性赋值来指定:

+ +
function loadFile(url, timeout, callback) {
+    var args = Array.prototype.slice.call(arguments, 3);
+    var xhr = new XMLHttpRequest();
+    xhr.ontimeout = function () {
+        console.error("The request for " + url + " timed out.");
+    };
+    xhr.onload = function() {
+        if (xhr.readyState === 4) {
+            if (xhr.status === 200) {
+                callback.apply(xhr, args);
+            } else {
+                console.error(xhr.statusText);
+            }
+        }
+    };
+    xhr.open("GET", url, true);
+    xhr.timeout = timeout;
+    xhr.send(null);
+}
+ +

你还可以为timeout事件的ontimeout事件句柄指定事件处理函数。

+ +

用法:

+ +
function showMessage (message) {
+    console.log(message + this.responseText);
+}
+
+loadFile("message.txt", 2000, showMessage, "New message!\n");
+ +

如上,我们指定的超时时间为 2000 ms。

+ +
+

timeout属性添加于Gecko 12.0  {{Gecko("12.0")}}。

+
+ +

同步请求

+ +
+

注意:从Gecko 30.0 {{ geckoRelease("30.0") }},Blink 39.0和Edge 13开始,主线程上的同步请求由于对用户体验的负面影响而被弃用。

+
+ +

同步XHR通常会导致网络挂起。但开发人员通常不会注意到这个问题,因为在网络状况不佳或服务器响应速度慢的情况下,挂起只会显示同步XHR现在处于弃用状态。建议开发人员远离这个API。

+ +

同步XHR不允许所有新的XHR功能(如timeoutabort)。这样做会调用InvalidAccessError

+ +

例子:HTTP 同步请求

+ +

这个例子演示了如何进行一个简单的同步请求.

+ +
var request = new XMLHttpRequest();
+request.open('GET', 'http://www.mozilla.org/', false);
+request.send(null);
+if (request.status === 200) {
+  console.log(request.responseText);
+}
+
+ +

第一行实例化一个XMLHttpRequest对象.第二行使用该对象打开一个HTTP请求,并指定使用HTTP GET方法来获取Mozilla.org主页内容,操作模式为同步.

+ +

第三行发送这个请求.参数为null表示GET请求不需要请求实体.

+ +

第四行为请求结束之后,检查请求状态码.如果状态码为200, 表示该请求成功,请求到的页面源文件会输出到控制台上.

+ +

例子: 在 Worker 中使用HTTP 同步请求

+ +

Worker中使用XMLHttpRequest时,同步请求比异步请求更适合.

+ +

example.html (主页):

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+  var oMyWorker = new Worker("myTask.js");
+  oMyWorker.onmessage = function(oEvent) {
+    alert("Worker said: " + oEvent.data);
+  };
+
+  oMyWorker.postMessage("Hello");
+</script>
+</head>
+<body></body>
+</html>
+
+ +

myFile.txt ( XMLHttpRequest对象同步请求的文件):

+ +
Hello World!!
+
+ +

myTask.js (包含了Worker代码):

+ +
self.onmessage = function (oEvent) {
+  if (oEvent.data === "Hello") {
+    var oReq = new XMLHttpRequest();
+    oReq.open("GET", "myFile.txt", false);  // 同步请求
+    oReq.send(null);
+    self.postMessage(oReq.responseText);
+  }
+};
+
+ +
注意:由于使用了Worker,所以该请求实际上也是异步的。
+ +

可以使用类似的方法,让脚本在后台与服务器交互,预加载某些内容。查看使用web workers了解更多详情。

+ +

将同步XHR用例调整到Beacon API

+ +

在某些情况下,XMLHttpRequest的同步使用是不可替代的,就像在window.onunloadwindow.onbeforeunload事件期间一样。 您应该考虑使用带有Keepalive标志的fetchAPI。 当keepalivefetch不可用时,可以考虑使用navigator.sendBeacon API可以支持这些用例,通常在提供良好UX的同时。

+ +

以下示例(来自sendBeacon文档)显示了一个理论分析代码,该代码尝试通过在卸载处理程序中使用同步XMLHttpRequest将数据提交给服务器。 这导致页面的卸载被延迟。

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    var client = new XMLHttpRequest();
+    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
+    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
+    client.send(analyticsData);
+}
+
+
+ +

使用sendBeacon()方法,当用户代理有机会的时候,数据将被异步传输到Web服务器,而不会延迟卸载或影响下一个导航的性能。

+ +

以下示例显示了使用sendBeacon()方法将数据提交给服务器的理论分析代码模式。

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    navigator.sendBeacon("/log", analyticsData);
+}
+
+ +

参见

+ + + +

{{ languages( {"en": "en/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

diff --git a/files/zh-cn/web/api/xmlhttprequest/timeout/index.html b/files/zh-cn/web/api/xmlhttprequest/timeout/index.html new file mode 100644 index 0000000000..941372fdf5 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/timeout/index.html @@ -0,0 +1,53 @@ +--- +title: XMLHttpRequest.timeout +slug: Web/API/XMLHttpRequest/timeout +tags: + - AJAX + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/timeout +--- +
{{APIRef('XMLHttpRequest')}}
+ +

XMLHttpRequest.timeout 是一个无符号长整型数,代表着一个请求在被自动终止前所消耗的毫秒数。默认值为 0,意味着没有超时。超时并不应该用在一个 {{Glossary('document environment')}} 中的同步 XMLHttpRequests  请求中,否则将会抛出一个 InvalidAccessError 类型的错误。当超时发生, timeout 事件将会被触发。{{gecko_minversion_inline("12.0")}}

+ +
+

注意:你不能在拥有的window中,给同步请求使用超时。

+
+ +

在异步请求中使用 timeout

+ +

在IE中,超时属性可能只能在调用 open() 方法之后且在调用 send() 方法之前设置。

+ +

示例

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+xhr.timeout = 2000; // 超时时间,单位是毫秒
+
+xhr.onload = function () {
+  // 请求完成。在此进行处理。
+};
+
+xhr.ontimeout = function (e) {
+  // XMLHttpRequest 超时。在此做某事。
+};
+
+xhr.send(null);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('XMLHttpRequest', '#the-timeout-attribute')}}{{Spec2('XMLHttpRequest')}}WHATW Gliving standard
diff --git a/files/zh-cn/web/api/xmlhttprequest/timeout_event/index.html b/files/zh-cn/web/api/xmlhttprequest/timeout_event/index.html new file mode 100644 index 0000000000..00d587fced --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/timeout_event/index.html @@ -0,0 +1,128 @@ +--- +title: timeout +slug: Web/API/XMLHttpRequest/timeout_event +tags: + - XHR + - XMLHttpRequest + - events + - timeout +translation_of: Web/API/XMLHttpRequest/timeout_event +--- +
+

当进度由于预定时间到期而终止时,会触发timeout 事件。

+
+ + + + + + + + + + + + + + + + + + + + +
冒泡
可取消
目标对象{{domxref("XMLHttpRequest")}}
接口{{domxref("ProgressEvent")}}
+ +

示例

+ +
var client = new XMLHttpRequest()
+  client.open("GET", "http://www.example.org/example.txt")
+  client.ontimeout = function(e) {
+    console.error("Timeout!!")
+  }
+  client.send()
+ +

继承

+ +

timeout 事件实现了 {{domxref("ProgressEvent")}} 接口,它继承自 {{domxref("Event")}} — 它拥有在这个接口上定义的属性和方法。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}} 
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/upload/index.html b/files/zh-cn/web/api/xmlhttprequest/upload/index.html new file mode 100644 index 0000000000..eed9701557 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/upload/index.html @@ -0,0 +1,116 @@ +--- +title: XMLHttpRequest.upload +slug: Web/API/XMLHttpRequest/upload +translation_of: Web/API/XMLHttpRequest/upload +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.upload 属性返回一个 {{domxref("XMLHttpRequestUpload")}}对象,用来表示上传的进度。这个对象是不透明的,但是作为一个{{domxref("XMLHttpRequestEventTarget")}},可以通过对其绑定事件来追踪它的进度。

+ +

可以被绑定在upload对象上的事件监听器如下:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件相应属性的信息类型
onloadstart获取开始
onprogress数据传输进行中
onabort获取操作终止
onerror获取失败
onload获取成功
ontimeout获取操作在用户规定的时间内未完成
onloadend获取完成(不论成功与否)
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-upload-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..0bc86f91bb --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,807 @@ +--- +title: 使用 XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest +tags: + - AJAX + - AJAXfile + - DOM + - HTTP + - JXON + - XHR + - XML + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +
 {{APIRef("XMLHttpRequest")}}
+ +

在该教程中,我们将使用{{domxref("XMLHttpRequest")}} 来发送 HTTP 请求以实现网站和服务器之间的数据交换。XMLHttpRequest常见和晦涩的使用情况都将包含在例子中。

+ +

发送一个 HTTP 请求,需要创建一个 XMLHttpRequest 对象,打开一个 URL,最后发送请求。当所有这些事务完成后,该对象将会包含一些诸如响应主体或 HTTP status 的有用信息。

+ +
function reqListener () {
+  console.log(this.responseText);
+}
+
+var oReq = new XMLHttpRequest();
+oReq.addEventListener("load", reqListener);
+oReq.open("GET", "http://www.example.org/example.txt");
+oReq.send();
+ +

请求类型

+ +

通过 XMLHttpRequest 生成的请求可以有两种方式来获取数据,异步模式或同步模式。请求的类型是由这个 XMLHttpRequest 对象的 open() 方法的第三个参数async的值决定的。如果该参数的值为 false,则该 XMLHttpRequest请求以同步模式进行,否则该过程将以异步模式完成。这两种类型请求的详细讨论和指南可以在同步和异步请求页找到。

+ +
注意:由于对用户体验的负面影响,从 Gecko 30.0{{geckoRelease("30.0")}}版本开始,在主线程上的同步请求已经被弃用。
+ +
注意:XMLHttpRequest 构造函数并不仅限于 XML 文档。它之所以使用“XML”开头是因为在它诞生之时,原先用于异步数据交换的主要格式便是XML。
+ +

处理响应

+ +

W3C规范定义了 {{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}} 对象的几种类型的响应属性。这些属性告诉客户端关于 XMLHttpRequest 返回状态的重要信息。一些处理非文本返回类型的用例,可能包含下面章节所描述的一些操作和分析。

+ +

分析并操作 responseXML属性

+ +

如果你使用 XMLHttpRequest 来获得一个远程的 XML 文档的内容,{{domxref("XMLHttpRequest.responseXML", "responseXML")}} 属性将会是一个由 XML 文档解析而来的 DOM 对象,这很难被操作和分析。这里有五种主要的分析 XML 文档的方式:

+ +
    +
  1. 使用 XPath 定位到文档的指定部分。
  2. +
  3. 手动 解析和序列化 XML 为字符串或对象。
  4. +
  5. 使用 XMLSerializer 把 DOM 树序列化成字符串或文件。
  6. +
  7. 如果你预先知道 XML 文档的内容,你可以使用 RegExp。如果你用 RegExp 扫描时受到换行符的影响,你也许想要删除所有的换行符。然而,这种方法是"最后手段",因为如果 XML 代码发生轻微变化,该方法将可能失败。
  8. +
+ +
注意: 在 W3C XMLHttpRequest 规范中允许 HTML 通过 XMLHttpRequest.responseXML 属性进行解析。更多详细内容请阅读 HTML in XMLHttpRequest 。本条注意已在英文原文中更新。
+ +
+

注意: XMLHttpRequest 现在可以使用 {{domxref("XMLHttpRequest.responseXML", "responseXML")}} 属性解释 HTML。请阅读 HTML in XMLHttpRequest 这篇文章了解相关用法。

+
+ +

解析和操作包含 HTML 文档的 responseText 属性

+ +

如果使用 XMLHttpRequest 从远端获取一个 HTML 页面,则所有 HTML 标记会以字符串的形式存放在responseText 属性里,这样就使得操作和解析这些标记变得困难。解析这些HTML标记主要有三种方式:

+ +
    +
  1. 使用 XMLHttpRequest.responseXML 属性。
  2. +
  3. 将内容通过 fragment.body.innerHTML 注入到一个 文档片段 中,并遍历 DOM 中的片段。
  4. +
  5. 如果你预先知道 HTML 文档的内容,你可以使用 RegExp 。如果你用 RegExp 扫描时受到换行符的影响,你也许想要删除所有的换行符。 然而,这种方法是"最后手段",因为如果 HTML 代码发生轻微变化,该方法将可能失败。
  6. +
+ +

处理二进制数据

+ +

尽管 {{domxref("XMLHttpRequest")}} 一般用来发送和接收文本数据,但其实也可以发送和接收二进制内容。有许多经过良好测试的方法来强制使用 XMLHttpRequest 发送二进制数据。利用 XMLHttpRequest 对象 {{domxref("XMLHttpRequest.overrideMimeType", "overrideMimeType()")}} 方法是一个解决方案,虽然它并不是一个标准方法。

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", url);
+// 以二进制字符串形式检索未处理的数据
+oReq.overrideMimeType("text/plain; charset=x-user-defined");
+/* ... */
+
+ +

然而,自从 {{domxref("XMLHttpRequest.responseType", "responseType")}} 属性目前支持大量附加的内容类型后,已经出现了很多的现代技术,它们使得发送和接收二进制数据变得更加容易。

+ +

例如,考虑以下代码,它使用 "arraybuffer" 的 responseType 来将远程内容获取到一个存储原生二进制数据的 {{jsxref("ArrayBuffer")}} 对象中。

+ +
var oReq = new XMLHttpRequest();
+
+oReq.onload = function(e) {
+  var arraybuffer = oReq.response; // 不是 responseText !
+  /* ... */
+}
+oReq.open("GET", url);
+oReq.responseType = "arraybuffer";
+oReq.send();
+ +

更多示例请参考 发送和接收二进制数据

+ +

监测进度

+ +

XMLHttpRequest 提供了各种在请求被处理期间发生的事件以供监听。这包括定期进度通知、 错误通知,等等。

+ +

支持 DOM 的 progress 事件监测之于 XMLHttpRequest 传输,遵循 Web API 进度事件规范:这些事件实现了 {{domxref("ProgressEvent")}} 接口。

+ +
+
{{event("progress")}}
+
检索的数据量发生了变化。
+
{{event("load")}}
+
传输完成,所有数据保存在 response 中。
+
+ +
var oReq = new XMLHttpRequest();
+
+oReq.addEventListener("progress", updateProgress);
+oReq.addEventListener("load" , transferComplete);
+oReq.addEventListener("error", transferFailed  );
+oReq.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+// ...
+
+// 服务端到客户端的传输进程(下载)
+function updateProgress (oEvent) {
+  if (oEvent.lengthComputable) {
+    var percentComplete = oEvent.loaded / oEvent.total * 100;
+    // ...
+  } else {
+    // 总大小未知时不能计算进程信息
+  }
+}
+
+function transferComplete(evt) {
+  console.log("The transfer is complete.");
+}
+
+function transferFailed(evt) {
+  console.log("An error occurred while transferring the file.");
+}
+
+function transferCanceled(evt) {
+  console.log("The transfer has been canceled by the user.");
+}
+ +

第 3-6 行为多种事件添加了事件监听,这些事件在使用 XMLHttpRequest 执行数据传输时被发出。

+ +
注意: 你需要在请求调用 open() 之前添加事件监听。否则 progress 事件将不会被触发。
+ +

在上一个例子中,progress 事件被指定由 updateProgress() 函数处理,并接收到传输的总字节数和已经传输的字节数,它们分别在事件对象的 totalloaded 属性里。但是如果 lengthComputable 属性的值是 false,那么意味着总字节数是未知并且 total 的值为零。

+ +

progress 事件同时存在于下载和上传的传输。下载相关事件在 XMLHttpRequest 对象上被触发,就像上面的例子一样。上传相关事件在 XMLHttpRequest.upload 对象上被触发,像下面这样:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.upload.addEventListener("progress", updateProgress);
+oReq.upload.addEventListener("load" , transferComplete);
+oReq.upload.addEventListener("error", transferFailed  );
+oReq.upload.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+ +
注意:progress 事件在使用 file: 协议的情况下是无效的。
+ +
注意:从 {{Gecko("9.0")}} 开始,进度事件现在可以依托于每一个传入的数据块,包括进度事件被触发前在已经接受了最后一个数据包且连接已经被关闭的情况下接收到的最后一个块。这种情况下,当该数据包的 load 事件发生时 progress 事件会被自动触发。这使你可以只关注 progress 事件就可以可靠的监测进度。
+ +
注意:在 {{Gecko("12.0")}} 中,当 responseType 为 "moz-blob" 时,如果你的 progress 事件被触发,则响应的值是一个包含了接收到的数据的 {{domxref("Blob")}} 。
+ +

使用 loadend 事件可以侦测到所有的三种加载结束条件(abortload,或 error):

+ +
req.addEventListener("loadend", loadEnd);
+
+function loadEnd(e) {
+  console.log("The transfer finished (although we don't know if it succeeded or not).");
+}
+
+ +

需要注意的是,没有方法可以确切的知道 loadend 事件接收到的信息是来自何种条件引起的操作终止;但是你可以在所有传输结束的时候使用这个事件处理。

+ +

提交表单和上传文件

+ +

XMLHttpRequest 的实例有两种方式提交表单:

+ + + +

第二种方式(使用 FormData API)是最简单最快捷的,但是缺点是被收集的数据无法使用 JSON.stringify() 转换为一个 JSON 字符串。
+ 只使用 AJAX 则更为复杂,但也更灵活、更强大。

+ +

仅使用 XMLHttpRequest

+ +

在大多数用例中,提交表单时即便不使用 FormData API 也不会要求其他的 API。唯一的例外情况是,如果你要上传一个或多个文件,你需要额外的 FileReader API。

+ +

提交方法简介

+ +

一个 html {{ HTMLElement("form") }} 可以用以下四种方式发送:

+ + + +

现在,我们提交一个表单,它里面有两个字段,分别被命名为 foobaz。如果你用 POST 方法,那么服务器将会接收到一个字符串类似于下面三种情况之一,其中的区别依赖于你采用何种编码类型:

+ + + +
Content-Type: application/x-www-form-urlencoded
+
+foo=bar&baz=The+first+line.%0D%0AThe+second+line.%0D%0A
+ + + +

相反的,如果你用 GET 方法,像下面这样的字符串将被简单的附加到 URL:

+ +
?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.
+ +

一个小框架

+ +

所有这些事情都是由浏览器在你提交一个 {{ HTMLElement("form") }} 的时候自动完成的。但是如果你想要用 JavaScript 做同样的事情,你不得不告诉解释器所有的事。那么,如何发送表单这件事在使用纯粹的 AJAX 时会复杂到无法在这里解释清楚。基于这个原因,我们提供一个完整的(但仍然教条的)框架,它可以使用所有的四种提交方式,甚至上传文件:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Sending forms with pure AJAX &ndash; MDN</title>
+<script type="text/javascript">
+
+"use strict";
+
+/*\
+|*|
+|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polyfill ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
+\*/
+
+if (!XMLHttpRequest.prototype.sendAsBinary) {
+  XMLHttpRequest.prototype.sendAsBinary = function(sData) {
+    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
+    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
+      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
+    }
+    /* send as ArrayBufferView...: */
+    this.send(ui8Data);
+    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
+  };
+}
+
+/*\
+|*|
+|*|  :: AJAX Form Submit Framework ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
+|*|
+|*|  This framework is released under the GNU Public License, version 3 or later.
+|*|  https://www.gnu.org/licenses/gpl-3.0-standalone.html
+|*|
+|*|  Syntax:
+|*|
+|*|   AJAXSubmit(HTMLFormElement);
+\*/
+
+var AJAXSubmit = (function () {
+
+  function ajaxSuccess () {
+    /* console.log("AJAXSubmit - Success!"); */
+    console.log(this.responseText);
+    /* you can get the serialized data through the "submittedData" custom property: */
+    /* console.log(JSON.stringify(this.submittedData)); */
+  }
+
+  function submitData (oData) {
+    /* the AJAX request... */
+    var oAjaxReq = new XMLHttpRequest();
+    oAjaxReq.submittedData = oData;
+    oAjaxReq.onload = ajaxSuccess;
+    if (oData.technique === 0) {
+      /* method is GET */
+      oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/,
+          oData.segments.length > 0 ? "?" + oData.segments.join("&") : ""), true);
+      oAjaxReq.send(null);
+    } else {
+      /* method is POST */
+      oAjaxReq.open("post", oData.receiver, true);
+      if (oData.technique === 3) {
+        /* enctype is multipart/form-data */
+        var sBoundary = "---------------------------" + Date.now().toString(16);
+        oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
+        oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" +
+            oData.segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
+      } else {
+        /* enctype is application/x-www-form-urlencoded or text/plain */
+        oAjaxReq.setRequestHeader("Content-Type", oData.contentType);
+        oAjaxReq.send(oData.segments.join(oData.technique === 2 ? "\r\n" : "&"));
+      }
+    }
+  }
+
+  function processStatus (oData) {
+    if (oData.status > 0) { return; }
+    /* the form is now totally serialized! do something before sending it to the server... */
+    /* doSomething(oData); */
+    /* console.log("AJAXSubmit - The form is now serialized. Submitting..."); */
+    submitData (oData);
+  }
+
+  function pushSegment (oFREvt) {
+    this.owner.segments[this.segmentIdx] += oFREvt.target.result + "\r\n";
+    this.owner.status--;
+    processStatus(this.owner);
+  }
+
+  function plainEscape (sText) {
+    /* How should I treat a text/plain form encoding?
+       What characters are not allowed? this is what I suppose...: */
+    /* "4\3\7 - Einstein said E=mc2" ----> "4\\3\\7\ -\ Einstein\ said\ E\=mc2" */
+    return sText.replace(/[\s\=\\]/g, "\\$&");
+  }
+
+  function SubmitRequest (oTarget) {
+    var nFile, sFieldType, oField, oSegmReq, oFile, bIsPost = oTarget.method.toLowerCase() === "post";
+    /* console.log("AJAXSubmit - Serializing form..."); */
+    this.contentType = bIsPost && oTarget.enctype ? oTarget.enctype : "application\/x-www-form-urlencoded";
+    this.technique = bIsPost ?
+        this.contentType === "multipart\/form-data" ? 3 : this.contentType === "text\/plain" ? 2 : 1 : 0;
+    this.receiver = oTarget.action;
+    this.status = 0;
+    this.segments = [];
+    var fFilter = this.technique === 2 ? plainEscape : escape;
+    for (var nItem = 0; nItem < oTarget.elements.length; nItem++) {
+      oField = oTarget.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE" && oField.files.length > 0) {
+        if (this.technique === 3) {
+          /* enctype is multipart/form-data */
+          for (nFile = 0; nFile < oField.files.length; nFile++) {
+            oFile = oField.files[nFile];
+            oSegmReq = new FileReader();
+            /* (custom properties:) */
+            oSegmReq.segmentIdx = this.segments.length;
+            oSegmReq.owner = this;
+            /* (end of custom properties) */
+            oSegmReq.onload = pushSegment;
+            this.segments.push("Content-Disposition: form-data; name=\"" +
+                oField.name + "\"; filename=\"" + oFile.name +
+                "\"\r\nContent-Type: " + oFile.type + "\r\n\r\n");
+            this.status++;
+            oSegmReq.readAsBinaryString(oFile);
+          }
+        } else {
+          /* enctype is application/x-www-form-urlencoded or text/plain or
+             method is GET: files will not be sent! */
+          for (nFile = 0; nFile < oField.files.length;
+              this.segments.push(fFilter(oField.name) + "=" + fFilter(oField.files[nFile++].name)));
+        }
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
+        /* NOTE: this will submit _all_ submit buttons. Detecting the correct one is non-trivial. */
+        /* field type is not FILE or is FILE but is empty */
+        this.segments.push(
+          this.technique === 3 ? /* enctype is multipart/form-data */
+            "Content-Disposition: form-data; name=\"" + oField.name + "\"\r\n\r\n" + oField.value + "\r\n"
+          : /* enctype is application/x-www-form-urlencoded or text/plain or method is GET */
+            fFilter(oField.name) + "=" + fFilter(oField.value)
+        );
+      }
+    }
+    processStatus(this);
+  }
+
+  return function (oFormElement) {
+    if (!oFormElement.action) { return; }
+    new SubmitRequest(oFormElement);
+  };
+
+})();
+
+</script>
+</head>
+<body>
+
+<h1>Sending forms with pure AJAX</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h2>Using the POST method</h2>
+<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
+
+<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: text/plain</h3>
+
+<form action="register.php" method="post" enctype="text/plain"
+    onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      Your name: <input type="text" name="user" />
+    </p>
+    <p>
+      Your message:<br />
+      <textarea name="message" cols="40" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: multipart/form-data</h3>
+
+<form action="register.php" method="post" enctype="multipart/form-data"
+    onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Upload example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" /><br />
+      Sex:
+      <input id="sex_male" type="radio" name="sex" value="male" />
+      <label for="sex_male">Male</label>
+      <input id="sex_female" type="radio" name="sex" value="female" />
+      <label for="sex_female">Female</label><br />
+      Password: <input type="password" name="secret" /><br />
+      What do you prefer:
+      <select name="image_type">
+        <option>Books</option>
+        <option>Cinema</option>
+        <option>TV</option>
+      </select>
+    </p>
+    <p>
+      Post your photos:
+      <input type="file" multiple name="photos[]">
+    </p>
+    <p>
+      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" />
+      <label for="vehicle_bike">I have a bike</label><br />
+      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" />
+      <label for="vehicle_car">I have a car</label>
+    </p>
+    <p>
+      Describe yourself:<br />
+      <textarea name="description" cols="50" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+</body>
+</html>
+
+ +

要测试它的话,创建一个名为 register.php 的页面(作为示例表单的 action 属性)并且只输入以下内容:

+ +
<?php
+/* register.php */
+
+header("Content-type: text/plain");
+
+/*
+NOTE: You should never use `print_r()` in production scripts, or
+otherwise output client-submitted data without sanitizing it first.
+Failing to sanitize can lead to cross-site scripting vulnerabilities.
+*/
+
+echo ":: data received via GET ::\n\n";
+print_r($_GET);
+
+echo "\n\n:: Data received via POST ::\n\n";
+print_r($_POST);
+
+echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n";
+if (isset($HTTP_RAW_POST_DATA)) { echo $HTTP_RAW_POST_DATA; }
+
+echo "\n\n:: Files received ::\n\n";
+print_r($_FILES);
+ +

激活这些代码的语法很简单:

+ +
AJAXSubmit(myForm);
+ +
注意: 该框架使用 {{domxref("FileReader")}} API 进行文件的上传。这是一个较新的 API 并且还未在 IE9 及以下版本的浏览器中实现。因此,使用 AJAX 上传仍是一项实验性的技术。如果你不需要上传 二进制文件,该框架在大多数浏览器中运行良好。
+ +
注意: 发送二进制内容的最佳途径是通过 {{jsxref("ArrayBuffer", "ArrayBuffers")}} 或 {{domxref("Blob", "Blobs")}} 结合 {{domxref("XMLHttpRequest.send()", "send()")}} 方法甚至 FileReader API 的 {{domxref("FileReader.readAsArrayBuffer()", "readAsArrayBuffer()")}} 方法。但是,自从该脚本的目的变成处理 可字符串化 的原始数据以来,我们使用 {{domxref("XMLHttpRequest.sendAsBinary()", "sendAsBinary()")}} 方法结合 FileReader API 的 {{domxref("FileReader.readAsBinaryString()", "readAsBinaryString()")}} 方法。同样地,上述脚本仅当你处理小文件时行之有效。如果不打算上传二进制内容,就考虑使用 FormData API 来替代。
+ +
注意: 非标准的 sendAsBinary 方法从 Gecko 31 {{geckoRelease(31)}} 开始将会废弃并且会很快被移除。标准方法 send(Blob data) 将会取而代之。
+ +

使用 FormData 对象

+ +

{{domxref("XMLHttpRequest.FormData", "FormData")}} 构造函数能使你编译一个键/值对的集合,然后使用 XMLHttpRequest 发送出去。其主要用于发送表格数据,但是也能被单独用来传输表格中用户指定的数据。传输的数据格式与表格使用 submit() 方法发送数据的格式一致,如果该表格的编码类型被设为 "multipart/form-data". FormData 对象可以被结合 XMLHttpRequest 的多种方法利用。例如,想了解如何利用 FormData 与 XMLHttpRequests, 请转到 Using FormData Objects 页面。为了说教的目的,这里有一个早期的例子,被转译成了使用 FormData API 的形式。注意以下代码片段:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" charset="UTF-8" />
+<title>Sending forms with FormData &ndash; MDN</title>
+<script>
+"use strict";
+
+function ajaxSuccess () {
+  console.log(this.responseText);
+}
+
+function AJAXSubmit (oFormElement) {
+  if (!oFormElement.action) { return; }
+  var oReq = new XMLHttpRequest();
+  oReq.onload = ajaxSuccess();
+  if (oFormElement.method.toLowerCase() === "post") {
+    oReq.open("post", oFormElement.action);
+    oReq.send(new FormData(oFormElement));
+  } else {
+    var oField, sFieldType, nFile, sSearch = "";
+    for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) {
+      oField = oFormElement.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ?
+          oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE") {
+        for (nFile = 0; nFile < oField.files.length;
+            sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name));
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
+        sSearch += "&" + escape(oField.name) + "=" + escape(oField.value);
+      }
+    }
+    oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), true);
+    oReq.send(null);
+  }
+}
+</script>
+</head>
+<body>
+
+<h1>Sending forms with FormData</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h2>Using the POST method</h2>
+<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
+
+<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: text/plain</h3>
+
+<p>The text/plain encoding is not supported by the FormData API.</p>
+
+<h3>Enctype: multipart/form-data</h3>
+
+<form action="register.php" method="post" enctype="multipart/form-data"
+    onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Upload example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" /><br />
+      Sex:
+      <input id="sex_male" type="radio" name="sex" value="male" />
+      <label for="sex_male">Male</label>
+      <input id="sex_female" type="radio" name="sex" value="female" />
+      <label for="sex_female">Female</label><br />
+      Password: <input type="password" name="secret" /><br />
+      What do you prefer:
+      <select name="image_type">
+        <option>Books</option>
+        <option>Cinema</option>
+        <option>TV</option>
+      </select>
+    </p>
+    <p>
+      Post your photos:
+      <input type="file" multiple name="photos[]">
+    </p>
+    <p>
+      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" />
+      <label for="vehicle_bike">I have a bike</label><br />
+      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" />
+      <label for="vehicle_car">I have a car</label>
+    </p>
+    <p>
+      Describe yourself:<br />
+      <textarea name="description" cols="50" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+</body>
+</html>
+
+ +
注意: 如之前所述,{{domxref("FormData")}} 对象并不是 可字符串化(stringifiable) 的对象。如果你想要字符串化一个提交数据,请使用这个 早期的纯 AJAX 例子. 同时也要注意,尽管这个例子中有一些 file {{ HTMLElement("input") }} 字段,但当你通过 FormData API 提交一个表格时,也无须使用 {{domxref("FileReader")}} API: 文件被自动加载并上传。
+ +

获取最后修改日期

+ +
function getHeaderTime () {
+  console.log(this.getResponseHeader("Last-Modified"));  /* 一个合法的 GMTString 日期或 null */
+}
+
+var oReq = new XMLHttpRequest();
+oReq.open("HEAD" /* 仅需要头部信息(headers)时请使用 HEAD! */, "yourpage.html");
+oReq.onload = getHeaderTime;
+oReq.send();
+ +

最后修改日期改变后的操作

+ +

先创建两个函数:

+ +
function getHeaderTime () {
+  var nLastVisit = parseFloat(window.localStorage.getItem('lm_' + this.filepath));
+  var nLastModif = Date.parse(this.getResponseHeader("Last-Modified"));
+
+  if (isNaN(nLastVisit) || nLastModif > nLastVisit) {
+    window.localStorage.setItem('lm_' + this.filepath, Date.now());
+    isFinite(nLastVisit) && this.callback(nLastModif, nLastVisit);
+  }
+}
+
+function ifHasChanged(sURL, fCallback) {
+  var oReq = new XMLHttpRequest();
+  oReq.open("HEAD" /* 使用 HEAD - 我们仅需要头部信息(headers)! */, sURL);
+  oReq.callback = fCallback;
+  oReq.filepath = sURL;
+  oReq.onload = getHeaderTime;
+  oReq.send();
+}
+ +

And to test:

+ +
/* 测试一下这个文件:"yourpage.html"... */
+
+ifHasChanged("yourpage.html", function (nModif, nVisit) {
+  console.log("The page '" + this.filepath + "' has been changed on " + (new Date(nModif)).toLocaleString() + "!");
+});
+ +

如果你想要了解 当前页面是否发生了改变,请阅读这篇文章:{{domxref("document.lastModified")}}.

+ +

跨站的 XMLHttpRequest

+ +

现代浏览器可以通过执行 WebApps 工作小组通过的 Access Control for Cross-Site Requests 标注来支持跨站请求。只要服务器端的配置允许您从您的 Web 应用发送请求,就可以使用 XMLHttpRequest 。 否则,会抛出一个 INVALID_ACCESS_ERR 异常

+ +

绕过缓存

+ +

一般地,如果缓存中有相应内容, XMLHttpRequest 会试图从缓存中读取内容。绕过缓存的方法见下述代码:

+ +
var req = new XMLHttpRequest();
+req.open('GET', url, false);
+req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
+req.send(null);
+ +
Note: 这个方法只工作于基于 Gecko内核的软件, 也就是通道属性是 Gecko-specific.
+ +

还有一个跨浏览器兼容的方法,就是给 URL 添加时间戳。请确保你酌情地添加了 "?" or "&" 。例如,将:

+ +
http://foo.com/bar.html -> http://foo.com/bar.html?12345
+http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345
+
+ +

因为本地缓存都是以 URL 作为索引的,这样就可以使每个请求都是唯一的,也就可以这样来绕开缓存。

+ +

你也可以用下面的方法自动更改缓存:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime());
+oReq.send(null);
+ +

安全性

+ +

{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy.<policyname>.XMLHttpRequest.open</policyname> to allAccess to give specific sites cross-site access. This is no longer supported.")}}

+ +

{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\"); to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}

+ +

要启用跨站脚本,推荐的做法是对 XMLHttpRequest 的响应使用 the Access-Control-Allow-Origin 的 HTTP 头。

+ +

XMLHttpRequests 被停止

+ +

如果你的 XMLHttpRequest 收到 status=0statusText=null 的返回,这意味着请求无法执行。 就是无法发送. 一个可能导致的原因是当 XMLHttpRequest origin (创建的 XMLHttpRequest) 改变时,XMLHttpRequest 执行 open().。这种情况是可能发生的,举个例子,我们在一个窗口的onunload事件中关闭XMLHttpRequest,但实际上在即将关闭窗口时,之前创建的XMLHttpRequest仍然在那里,最后当这个窗口失去焦点、另一个窗口获得焦点时,它还是发送了请求(也就是open())。最有效的避免这个问题的方法是为新窗口的{{event("activate")}}事件设置一个监听器,一旦窗口关闭,它的{{event("unload")}}事件便触发。

+ +

Worker

+ +

设置 overrideMimeType  后在 {{domxref("Worker")}} 中无法正常工作,详见 {{bug(678057)}}。其他浏览器也许会以不同的手段处理。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

浏览器兼容性

+ + + +

{{Compat("api.XMLHttpRequest")}}

+ +

参考资料

+ +
    +
  1. MDC AJAX introduction
  2. +
  3. HTML in XMLHttpRequest
  4. +
  5. HTTP access control
  6. +
  7. How to check the security state of an XMLHTTPRequest over SSL
  8. +
  9. XMLHttpRequest - REST and the Rich User Experience
  10. +
  11. Microsoft documentation
  12. +
  13. Apple developers' reference
  14. +
  15. "Using the XMLHttpRequest Object" (jibbering.com)
  16. +
  17. The XMLHttpRequest Object: W3C Specification
  18. +
  19. Web Progress Events specification
  20. +
  21. Reading Ogg files with JavaScript (Chris Double)
  22. +
diff --git a/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest_in_ie6/index.html b/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest_in_ie6/index.html new file mode 100644 index 0000000000..2c1231a04a --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/using_xmlhttprequest_in_ie6/index.html @@ -0,0 +1,28 @@ +--- +title: 在 IE6 中使用 XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest_in_IE6 +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest_in_IE6 +--- +

XMLHttpRequest 在 Internet Explorer 5.0 上作为 ActiveX 控件第一次被 Microsoft 引入。然而,在 IE7 和其它浏览器上,XMLHttpRequest 作为本地 JavaScript 对象而存在。

+ +

在现代的浏览器上,你可以使用下面的代码创建一个新的 XMLHttpRequest 对象:

+ +
var request = new XMLHttpRequest()
+
+ +

如果你需要支持 Internet Explorer 6 和更老的浏览器,你需要像下方所示扩展你的代码:

+ +
if (window.XMLHttpRequest) {
+    //Firefox、 Opera、 IE7 和其它浏览器使用本地 JavaScript 对象
+    var request = new XMLHttpRequest();
+} else {
+    //IE 5 和 IE 6 使用 ActiveX 控件
+    var request = new ActiveXObject("Microsoft.XMLHTTP");
+}
+
+ +

更多

+ + diff --git a/files/zh-cn/web/api/xmlhttprequest/withcredentials/index.html b/files/zh-cn/web/api/xmlhttprequest/withcredentials/index.html new file mode 100644 index 0000000000..d91fa7cc87 --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/withcredentials/index.html @@ -0,0 +1,103 @@ +--- +title: XMLHttpRequest.withCredentials +slug: Web/API/XMLHttpRequest/withCredentials +tags: + - AJAX + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/withCredentials +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.withCredentials  属性是一个{{jsxref("Boolean")}}类型,它指示了是否该使用类似cookies,authorization headers(头部授权)或者TLS客户端证书这一类资格证书来创建一个跨站点访问控制(cross-site Access-Control)请求。在同一个站点下使用withCredentials属性是无效的。

+ +

此外,这个指示也会被用做响应中cookies 被忽视的标示。默认值是false。

+ +

如果在发送来自其他域的XMLHttpRequest请求之前,未设置withCredentials 为true,那么就不能为它自己的域设置cookie值。而通过设置withCredentials 为true获得的第三方cookies,将会依旧享受同源策略,因此不能被通过document.cookie或者从头部相应请求的脚本等访问。

+ +
+

注: 永远不会影响到同源请求

+
+ +
+

Note: 不同域下的XmlHttpRequest 响应,不论其Access-Control- header 设置什么值,都无法为它自身站点设置cookie值,除非它在请求之前将withCredentials 设为true。

+
+ +

实例

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', 'http://example.com/', true);
+xhr.withCredentials = true;
+xhr.send(null);
+ +

详述

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-withcredentials-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(3)}}{{CompatGeckoDesktop("1.9.1")}}[2]{{CompatIe(10)}}[1]{{CompatOpera(12)}}{{CompatSafari("4")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1]IE8 和IE9通过使用  XDomainRequest 支持跨域请求

+ +

[2] 从 Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8)开始, Gecko 不允许在同步请求下使用withCredentials 属性.尝试这么做将会导致浏览器抛出 NS_ERROR_DOM_INVALID_ACCESS_ERR exception的错误.

diff --git a/files/zh-cn/web/api/xmlhttprequest/xmlhttprequest/index.html b/files/zh-cn/web/api/xmlhttprequest/xmlhttprequest/index.html new file mode 100644 index 0000000000..57d2ad87da --- /dev/null +++ b/files/zh-cn/web/api/xmlhttprequest/xmlhttprequest/index.html @@ -0,0 +1,58 @@ +--- +title: XMLHttpRequest() +slug: Web/API/XMLHttpRequest/XMLHttpRequest +tags: + - API + - XHR + - XMLHttpRequest + - 参考 + - 构造函数 + - 构造器 +translation_of: Web/API/XMLHttpRequest/XMLHttpRequest +--- +

{{draft}}{{APIRef('XMLHttpRequest')}}

+ +

The XMLHttpRequest() 构造器初始化一个新的 {{domxref("XMLHttpRequest")}} 对象。

+ +

关于 XMLHttpRequest 的具体用法,请参考使用 XMLHttpRequest

+ +

语法

+ +
const request = new XMLHttpRequest();
+ +

参数

+ +

无。

+ +

返回值

+ +

一个新的 {{domxref("XMLHttpRequest")}} 对象。此对象 must be prepared by at least calling {{domxref("XMLHttpRequest.open", "open()")}} to initialize it before calling {{domxref("XMLHttpRequest.send", "send()")}} to send the request to the server.

+ +

非标准 Firefox 语法

+ +

Firefox 16 added a non-standard parameter to the constructor that can enable anonymous mode (see {{Bug("692677")}}). Setting the mozAnon flag to true effectively resembles the AnonXMLHttpRequest() constructor described in older versions of the XMLHttpRequest specification.

+ +

Gecko/Firefox 16 为该构造方法新增了一个非标准的参数,以启用匿名模式(参见 {{Bug("692677")}})。将 mozAnon 属性设置为 true,即可有效地模拟 AnonXMLHttpRequest() 构造器。此构造器在早先的 XMLHttpRequest 规范中有描述,但并未在任何浏览器中被实现。

+ +
const request = new XMLHttpRequest(paramsDictionary);
+ +

参数(非标准)

+ +
+
objParameters {{gecko_minversion_inline("16.0")}}
+
有两个属性可以设置: +
+
mozAnon
+
布尔值:将此属性设置为 true 将使浏览器在获取资源时不暴露自身来源和用户凭据。最重要的是,这意味着只有明确添加使用setRequestHeader才会发送cookies。
+
mozSystem
+
布尔值:将此属性设置为 true 允许建立跨站点的连接,而无需服务器选择使用CORS(译者注:Cross-Origin Resource Sharing 跨域资源共享)必须同时将参数 mozAnon 设置为 true即不能与cookie或其他用户凭据同时发送。仅限于在privileged (reviewed) apps起效(译者注:此句原文This only works in privileged (reviewed) apps;);在 Firefox 上任何网页加载后不起作用(译者注:此句原文 it does not work on arbitrary webpages loaded in Firefox.)。
+
+
+
+ +

参见

+ + -- cgit v1.2.3-54-g00ecf