当咱们声明了一个XMLHttpRequest对象的实例的时候,使用for-in来循环遍历一下这个实例(本文使用的是chrome45版本浏览器),咱们会发如今这个实例上绑定了一些内容,我把这些内容进行了一下分类:javascript
下面对这五个分类的前四个已经里面的内容进行一个详细的记录~(有人可能会问,不是上面分了五个分类吗,可素第五个分类就那5个不可改变的值,也没有什么好说的+_+)
1、配置项
① timeout
timeout是用来设置超时时间的,默认的值是0,也就是说没有超时限制,无论请求多久都不会触发超时。能够给他设置一个类型为数字的值,表明多少毫秒以后若是没有收到响应就触发超时事件(ontimeout)。
② withCredentials
这个值是来配置是否在发送的时候携带着凭据,默认值是false,也就是默认不携带。所谓的凭据指的就是cookie、HTTP认证及客户端SSL证实等信息。这个是在CORS跨域的时候与服务器的Access-Control-Allow-Credentials进行配合使用的,若是发送了携带凭据的请求,可是服务器的响应里面没有Access-Control-Allow-Credentials是true这个值的头,那么浏览器就会因为同源限制把响应给屏蔽掉,而且调用xhr的oerror事件。
例若有下面这一段代码:php
var xhr=new XMLHttpRequest(); xhr.withCredentials=true; xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ console.log("success!"); } } } xhr.onerror=function(e){ console.log("error!"); } xhr.open("GET","http://127.0.0.1/withCredentials.php"); xhr.send(null);
若是在服务端的代码试下嘛这样子的:
header("Access-Control-Allow-Origin: *"); echo "ok";
XMLHttpRequest cannot load http://127.0.0.1/withCredentials.php. Credentials flag is "true", but the "Access-Control-Allow-Credentials" header is "". It must be "true" to allow credentials. Origin "http://192.168.1.106" is therefore not allowed access.
header("Access-Control-Allow-Origin: http://192.168.1.106"); header("Access-Control-Allow-Credentials: true"); echo "ok";
if(xhr.readyState==4){ if(xhr.status>=200&&xhr.status<300 ||="" xhr.status="=304){" console.log(xhr.response);="" }="" }<="" code=""></300>
③ statusText
var xhr = new XMLHttpRequest(); var onProgressHandler = function(event) { if(event.lengthComputable) { console.log((event.loaded / event.total) * 100); } else { console.log("Can"t determine the size of the file."); } } xhr.upload.addEventListener("progress", onProgressHandler, false); xhr.open("POST","http://iwenku.net"); xhr.send(data);
3、方法项
var xhr=new XMLHttpRequest(); xhr.open("GET","http://127.0.0.1/openTest.php"); xhr.send(null); xhr.onreadystatechange=function(){ if(xhr.readyState===xhr.DONE){ console.log("done"); } } console.log("response"+xhr.responseText); for(var i=0;i<3;i++){ console.log(i);="" }<="" code=""></3;i++){>
上面open方法没有传入第三个参数,也就是使用了默认值true,表明这是一个异步的请求,最后程序的输出为:
var xhr=new XMLHttpRequest(); xhr.open("GET","http://127.0.0.1/getResponseHeader.php"); xhr.send(null); xhr.onreadystatechange=function(){ if(xhr.readyState===xhr.DONE){ console.log(xhr.getResponseHeader("Content-Type")); } }
上面这一段代码会输出”text/html“,也就是说在相应头中的Content-Type就是这个。