当我们声明了一个xmlhttprequest对象的实例的时候,使用for-in来循环遍历一下这个实例(本文使用的是chrome45版本浏览器),我们会发现在这个实例上绑定了一些内容,我把这些内容进行了一下分类:
下面对这五个分类的前四个已经里面的内容进行一个详细的记录~(有人可能会问,不是上面分了五个分类吗,可素第五个分类就那5个不可改变的值,也没有什么好说的+_+)
一、配置项
① timeout
timeout是用来设置超时时间的,默认的值是0,也就是说没有超时限制,不管请求多久都不会触发超时。可以给他设置一个类型为数字的值,代表多少毫秒之后如果没有收到响应就触发超时事件(ontimeout)。
② withcredentials
这个值是来配置是否在发送的时候携带着凭据,默认值是false,也就是默认不携带。所谓的凭据指的就是cookie、http认证及客户端ssl证明等信息。这个是在cors跨域的时候与服务器的access-control-allow-credentials进行配合使用的,如果发送了携带凭据的请求,但是服务器的响应里面没有access-control-allow-credentials是true这个值的头,那么浏览器就会由于同源限制把响应给屏蔽掉,并且调用xhr的oerror事件。
例如有下面这一段代码:
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);三、方法项
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就是这个。
如对本文有疑问, 点击进行留言回复!!
同事牛逼啊,写了个隐藏 bug,我排查了 3 天才解决问题!
【JavaScript笔记(一)】万丈高楼平地起 - 基本概念篇
轻松解决 org.apache.taglibs.standard.tlv.JstlCoreTLV 困惑
网友评论