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类型,表示请求的状态
例子:
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的值(包含在响应实体中)。
例子:
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("");}
返回一个包含响应数据的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
一个枚举类型用来定义响应类型
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);
对响应返回一个文档,或者如果请求不成功、请求还没发送或者不能将相应文本解析为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类型的数据,表示服务器返回的状态信息。
常见的状态信息如下:
例子:
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*/
表示一个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);
一个EventHandler,当请求超时时会调用。
XMLHttpRequest.upload
是一个XMLHttpRequestUpload,表示上传的进度。XMLHttpRequestUpload上传数据到客户端。
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
var xhr = new XMLHttpRequest(), method = "GET", url = "https://developer.mozilla.org/";xhr.open(method, url, true);xhr.send();xhr.abort();
语法: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()); }}
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")); }}
语法:
// 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();
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的区别:
XMLHttpRequest.setRequestHeader()
非标准方法
XMLHttpRequest.init()send()的变体,发送二进制数据。(只在某些浏览器中有用,不赞成使用)
浏览器适配情况
(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 support12No 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移动端:
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????- XMLHttpRequest
- XMLHttpRequest
- XMLHTTPRequest
- XMLHTTPRequest
- XMLHttpRequest
- XMLHttpRequest
- XMLHttpRequest
- XMLHttpRequest
- xmlhttprequest
- XMLHttpRequest
- XMLHttpRequest
- xmlhttprequest
- XMLHttpRequest
- XMLHttpRequest
- XMLHttpRequest
- XMLHttpRequest
- XMLHttpRequest
- XMLHttpRequest
- Spring学习(一)初识spring
- java——从文件中读取JSON
- QueryRunner 的Handler
- Zurmo(十七)之模块搜索
- Flask 学习篇一: 搭建Python虚拟环境,安装flask,并设计RESTful API。
- XMLHttpRequest
- 欢迎使用CSDN-markdown编辑器
- Github最火开源项目-GreenDao数据库使用
- Oracle基本操作七:序列,同义词,索引,视图
- 后台获取放在Request Payload中的值
- 使用Backupninja自动执行MySQL数据库备份
- Zookeeper集群搭建
- thinkphp5,tpshop5的sql跟踪器
- thinkphp前端显示被反编译详解