xhr.open(‘get’,‘/server’,true);
xhr.onreadystatechange=function(){
if(xhr.readyState!==4){
return
}
if(xhr.status>=200&&xhr.status<300){
console.log(xhr.responseText)
}
}
xhr.send(null)
3.timeout属性与ontimeout事件
- timeout属性表示请求在等待响应多少毫秒轴终止,如果在规定时间内没有接收到响应,那么就会触发ontimeout事件处理程序
const xhr=new XMLHttpRequest()
xhr.open(‘get’,‘/server’,true);
//将超市设置为3秒钟
xhr.timeout=3000;
//请求超时后请求会自动终止,会调用ontimeout事件处理程序
xhr.ontimeout=function(){
//处理代码
console.log(‘请求超时了’)
}
xhr.send(null);
4.overrideMimeType()方法
-
overrideMimeType()方法能够重写服务器返回的MIME类型,从而让浏览器进行不一样的处理。
-
假如服务器返回的数据类型是text/xml,由于种种原因浏览器解析不成功报错,这时就拿不到数据。为了拿到原始数据,我们可以把MIME类型改成text/plain,这样浏览器就不会去自动解析,从而我们就可以拿到原始文本了。
const xhr = new XMLHttpRequest()
xhr.open(‘get’, ‘/server’, true)
xhr.overrideMimeType(‘text/plain’)
xhr.send(null)
5.responseType属性
-
responseType属性是一个字符串,表示服务器返回数据的类型。使用xhr.response属性来接收
-
这个属性时可写的,可以在调用open()方法之后,send()方法之间设置这个属性值,告诉服务器返回指定类型的数据,如果responseType设为哦空字符串,等同于默认值text。
-
responseTye属性可以设置格式类型如下
| responseType属性的值 | response属性的数据类型与说明 |
| — | — |
| ”“ | String字符串 默认值,等同于text |
| ”text“ | String字符串 服务器返回文本数据 |
| ”document“ | Document对象 希望返回XML格式数据时使用 |
| ”json“ | javascript对象 IE10/IE11不支持 |
| ”blob“ | Blob对象 服务器返回二进制对象 |
| ”arrayBuffer | ArrayBuffer随心 服务器返沪二进制数组 |
-
当将reaponseType设置了一个特定类型时,你需要确保服务器返回的类型和你所设置的返回值类型时兼容的。如果两者类型不兼容,那么服务器返回的数据会变成null,及时服务器返回了数据
-
reaponseType只适用于异步请求,如果给同步请求设置了,那么将会抛出InvalidAccessError的异常
//使用responseTyep,以获取一张图片为例
const xhr=new XMLHttpRequest();
xhr.open(‘get’,‘/server/image.png’,true);
xhr.responseType=‘blob’//这里返回二进制类型的数据
xhr.οnlοad=function(){
if(xhr.status>=200&&xhr.status<300){
const blob=this.response
//…
}
}
xhr.send(null)
6.withCredentials属性
-
withCredentials属性是一个布尔值,表示跨域请求是否携带凭据信息(cookie、HTTP认证、以及客户端SSL证明等),默认为false
-
如果需要跨域Ajax请求发送Cookie,需要withCredentials属性设置为true