XMLHttpRequest

来源:互联网 发布:js中小于等于 编辑:程序博客网 时间:2024/05/20 20:48

原英文链接:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

参照原英文文章,翻译过来,然后加入自己的理解和拓展。

XMLHttpRequest是客户端(如浏览器)的一个API接口,提供一个客户端和服务器之间传输数据的功能。它使从一个URL获取数据变得容易而不用刷新整个页面。在更新页面一部分数据的同时不会打断用户的其它操作。XMLHttpRequest经常应用于AJAX编程。

XMLHttpRequest起初是由Microsoft设计实现的,最终被Mozilla,Apple和Google采纳。现在被WHATWG标准化。不管它的名字是什么,XMLHttpRequest可以被用来传输任何形式的数据,不仅仅是XML,还支持除了HTTP协议外的其它协议(包括file和ftp)。

EventTarget <--- XMLHttpRequestEventTarget <--- XMLHttpRequest

构造函数

XMLHttpRequest()

该构造函数初始化一个XMLHttpRequest。它必须在调用任何其它方法之前调用。

例子:

var myRequest = new XMLHttpRequest();

属性

XMLHttpRequest接口也继承XMLHttpRequestEventTarget和EventTarget的属性。

XMLHttpRequest.onreadystatechange

一个EventHandler,当readyState属性值改变时就会被调用。

语法: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();


XMLHttpRequest.readyState

返回unsigned short类型,表示请求的状态

ValueStateDescription0UNSENT请求已经创建,但是还没调用open()1OPENEDopen()已调用,在此期间,可以使用setRequestHeader()方法设置请求头2HEADERS_RECEIVEDsend()已调用,响应头已接收到3LOADING正在接收响应数据,如果responseType是“text”或者空字符串,responseText将会存储已加载的部分数据4DONE操作完成。返回成功或者失败








例子:

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


XMLHttpRequest.response

返回一个ArrayBuffer,Blob,Document,JavaScript对象,或者一个DOMString,取决于XMLHttpRequest.responseType的值(包含在响应实体中)。

Value of responseTypeData type of response property""DOMString(默认值)"arraybuffer"ArrayBuffer"blob"Blob"document"Document"json"JavaScript对象,从服务器返回的JSON字符串中解析出来"text"DOMString








例子:

var url = "somePage.html";function load(url, callback){    var xhr = new XMLHttpRequest();    xhr.onreadystatechange = function() {        if(xhr.readyState === 4){            console.log(xhr.response); // Outputs a DOMString by default        }    }    xhr.open("GET", url, true);    xhr.send("");}


XMLHttpRequest.responseText

返回一个包含响应数据的DOMString或者当请求不成功或者请求没发送时为null

例子:

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


XMLHttpRequest.responseType

一个枚举类型用来定义响应类型

ValueData type of response property""DOMString(默认值)"arraybuffer"ArrayBuffer"blob"Blob"document"Document"json"JavaScript对象,从服务器返回的JSON字符串中解析"text"DOMString







XMLHttpRequest.responseURL

返回响应的序列化URL或者当URL是null时返回空字符串

例子:

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


XMLHttpRequest.responseXML

对响应返回一个文档,或者如果请求不成功、请求还没发送或者不能将相应文本解析为XML或者HTML文档,就返回null。

语法: var data = XMLHttpRequest.responseXML;

例子:

var xhr = new XMLHttpRequest();xhr.open("GET", "server", true);// If specified, responseType must be empty string or "document"xhr.responseType = "document";// overrideMimeType() can be used to force the response to be parsed as XMLxhr.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);

readyState为客户端的状态信息,当readyState为xhr.DONE时,说明请求完成(成功或者失败);请求完成后,再去判断服务端返回的状态信息,如果status为200,说明请求成功,然后对数据做进一步处理。


XMLHttpRequest.status

返回一个unsigned short类型的数据,表示服务器返回的状态信息。

常见的状态信息如下:

statusdescription200ok(表示请求成功)304Not Modified400Bad Request(服务器不能理解发来的请求或者请求中包含语法错误)403Forbidden(客户端没有权限访问服务器)404Not Found500Internal Server Error502Bad Gateway









例子:

var xhr = new XMLHttpRequest();console.log("UNSET", 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);/*** Outputs the following:** UNSENT 0* OPENED 0* LOADING 200* DONE 200*/

XMLHttpRequest.statusText

返回一个HTTP服务器响应的DOMString字符串。与XMLHTTPRequest.status不同,这个字符串包含整个的响应状态信息(如“200 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);/*** Outputs the following:** 0 UNSENT* 1 OPENED* 3 LOADING OK* 4 DONE OK*/


XMLHttpRequest.timeout

表示一个unsigned long的毫秒值,如果一个请求在经过给定毫秒值后没有成功,该请求将被自动终止。
例子:

var xhr = new XMLHttpRequest();xhr.open("GET", "/server", true);xhr.timeout = 2000; // time in millisecondsxhr.onload = function () {    // Request finished. Do processing here.}xhr.ontimeout = function (e) {    // XMLHttpRequest timed out. Do something here.};xhr.send(null);


XMLHttpRequestEventTarget.ontimeout

一个EventHandler,当请求超时时会调用。


XMLHttpRequest.upload

是一个XMLHttpRequestUpload,表示上传的进度。XMLHttpRequestUpload上传数据到客户端。

EventListenersData type of response propertyonloadstart开始获取数据onprogress正在传输数据onabort获取数据操作被终止onerror获取数据失败onload获取数据成功ontimeout在限定的超时时间内,数据没有获取完成onloadend获取数据完成(成功或者失败)









XMLHttpRequest.withCredentials

一个boolean值,表明在跨站点的权限控制中是否需要证书,如cookies或者认证头。

例子:

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

非标准属性

XMLHttpRequest.channel

是一个nsIChannel(指定用特定的协议创建多个“GET”请求,并统一处理这些请求)。该通道将被XMLHttpRequest使用当处理request请求时。


XMLHttpRequest.mozAnon

是一个boolean值。如果是true,请求发送时将不带cookie和认证头。


XMLHttpRequest.mozSystem

是一个boolean值。如果是true,同样的原始策略将不会被执行(?不懂)。


XMLHttpRequest.mozBackgroundRequest

是一个boolean值。它表明对象是否表示一个后台服务请求。


XMLHttpRequest.mozResponseArrayBuffer

是一个ArrayBuffer。请求的响应结果,是一个JavaScript数组。


XMLHttpRequest.multipart

已废弃

Event Handlers

onreadystatechange作为XMLHttpRequest实例的一个属性,被所有浏览器支持。

尽管,不同的浏览器都有实现一些其它的事件句柄(onload,onerror,onprogress等等)。这些Firefox都支持。尤其,熟悉nsIXMLHttpRequestEventTarget和使用XMLHttpRequest。

近期一些浏览器,包括Firefox,除了为所有属性设置到一个处理函数外,也支持通过标准的addEventListener APIs来监听XMLHttpRequest事件。

Methods

XMLHttpRequest.abort()
当请求发送后终止。
语法:xhrInstance.abort();
例子:
var xhr = new XMLHttpRequest(),      method = "GET",      url = "https://developer.mozilla.org/";xhr.open(method, url, true);xhr.send();xhr.abort();

XMLHttpRequest.getAllResponseHeaders()
返回所有的响应头,以CRLF分隔为一个个字符串,或者当没有响应数据时返回null。
语法:var headers = request.getAllResponseHeaders();
例子:
var request = new XMLHttpRequest();request.open("GET", "foo.txt", true);request.send();request.onreadystatechange = function(){    if(this.readyState == this.HEADERS_RECEIVED){            console.log(request.getAllResponseHeaders());        }}

XMLHttpRequest.getResponseHeader()
返回一个包含指定头的值的字符串,或者响应没有收到时或者不存在对应头时,返回null。
语法:var myHeader = getResponseHeader(name);
例子:
var client = new XMLHttpRequest();client.open("GET", "unicorns-are-teh-awesome.txt", true);client.send();client.onreadystatechange = function(){    if(this.readyState == this.HEADERS_RECEIVED){           console.log(client.getResponseHeader("Content-Type"));         }}

XMLHttpRequest.open()
初始化一个请求。这个方法被用作在JavaScript中初始化一个http请求。
语法:
xhrReq.open(method, url);
xhrReq.open(method, url, async);
xhrReq.open(method, url, async, user);
xhrReq.open(method, url, async, user, password);
其中user和password参数用来进行认证,默认情况下,值为null。

XMLHttpRequest.overrideMimeType()
覆盖服务器返回的MIME类型。
例子:
// if the server doesn't specify, the returned text gets treated like xml// and when you receive plain text or something instead of xml// you get an error: XML Parsing Error: not well-formed// this shows how to receive plain text req = new XMLHttpRequest();req.overrideMimeType("text/plain");req.addEventListener("load", callback);req.open("get", url);req.send();

XMLHttpRequest.send()
发送请求。如果请求是异步的(默认),请求发出时,方法立即返回一个值。当是同步时,只有当服务器响应时,方法才返回值。
语法:
void send();void send(ArrayBuffer data);void send(ArrayBufferView data);void send(Blob data);void send(Document data);void send(DOMString? data);void send(FormData data);
例子:GET
var xhr = new XMLHttpRequest();xhr.open("GET", "/server", true);xhr.onload = function(){    // Request finished. Do processing here.};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);//Send the proper header information along with the requestxhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xhr.onreadystatechange = function(){//Call a function when the state changes.    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){        // Request finished. Do processing here.    }}xhr.send("foo=bar&lorem=ipsum");// xhr.send("string");// xhr.send(new Blob());// xhr.send(new Int8Array());// xhr.send({ form: "data" });// xhr.send(document);
GET与POST的区别:
GET发送数据到服务器时,大小有限制,且参数得在url中指定,会暴露在浏览器地址栏中,安全性低。send中参数指定为null。
POST发送数据到服务器时,大小没有限制,参数在send中设定,作为http消息实体的一部分。安全性高。

XMLHttpRequest.setRequestHeader()
设置HTTP请求头的值。你必须在open()后和send()前调用。
语法:myReq.setRequestHeader(header, value);

非标准方法

XMLHttpRequest.init()
初始化对象以便在C++中使用。
警告:该方法不能在JavaScript中调用。

XMLHttpRequest.openRequest()
用open()代替。

XMLHttpRequest.sendAsBinary()
send()的变体,发送二进制数据。(只在某些浏览器中有用,不赞成使用)

浏览器适配情况

PC端
FeatureChromeEdgeFirefox(Gecko)Internet ExplorerOperaSafari(Webkit)Basic support(XHR1)1(Yes)1.0 (1.7 or earlier)7(Yes)1.2send(ArrayBuffer)9

(Yes)9.0 (9.0)1011.60?send(ArrayBufferView)22(Yes)20.0(20.0)???send(Blob)7(Yes)3.6(1.9.2)1012?send(FormData)6(Yes)4.0 (2.0)1012?sendAsBinary(DOMString)No supportNo support2.0(1.8.1)No supportNo supportNo supportresponse10(Yes)6.0 (6.0)1011.60(Yes)responseType = "arraybuffer"10(Yes)6.0 (6.0)1011.60(Yes)responseType = 'blob'19(Yes)6.0 (6.0)1012(Yes)responseType = 'document'18(Yes)11.0(11.0)10No support6.1responseType = 'json'31No support10.0(10.0)No support12
No support
16
17(Yes)Progress Events7(Yes)3.5(1.9.1)1012(Yes)withCredentials3(Yes)3.5(1.9.1)10124timeout29.0(Yes)12.0(12.0)812
16(Yes)responseType = 'moz-blob'No supportNo support12.0(12.0)No supportNo supportNo support




















移动端:

FeatureAndroidChrome for AndroidEdgeFirefox Mobile(Gecko)IE PhoneOpera MobileSafari MobileBasic support?1.0(Yes)(Yes)???send(ArrayBuffer)??(Yes)????send(ArrayBufferView)??(Yes)????send(Blob)??(Yes)????send(FormData)??(Yes)????sendAsBinary(DOMString)??No support????response??(Yes)????responseType = 'arraybuffer'??(Yes)????responseType = 'blob'??(Yes)????responseType = 'document'??(Yes)????responseType = 'json'??No support????Progress Events??(Yes)????withCredentials??(Yes)????timeout??(Yes)????responseType = 'moz-blob'??No support????












0 0