XHRHttpRequest
使用方式
var xhr = new XMLHttpRequest() xhr.timeout = 2000; // 超时时间,单位是毫秒 // onreadystatechange会在状态改变的时候触发 xhr.onreadystatechange = function () { // 0 UNSENT 表示代理创建,但是还未连接 // 1 OPENED 已经连接 调用了open()方法 // 2 HEADERS_RECEIVED send()方法已经被调用, 头部和状态已经可以获得 // 3 LOADING 下载中 // 4 DONE 完成 if (xhr.readyState === 4 && xhr.status === 200) { //... } } xhr.onabort = function () { // 出錯 } xhr.ontimeout = function (e) { // XMLHttpRequest 超时。在此做某事。 }; xhr.open('GET', url) xhr.responseType = 'document' //需要在open方法之后调用,在send之前 通过特定的类型请求数据 xhr.send()
主要方法: onreadystatechange(), onabort(), ontimeout(), onload(), open(), send()
主要屬性:
1. readyState: 請求狀態有五種
0 | 1 | 2 | 3 | 4 |
UNSENT | OPENED | HEADERS_RECEIVED | LOADING | DONE |
2. status:請求返回的狀態值 詳情見 http://www.runoob.com/http/http-status-codes.html
100 | 200 | 300 | 400 | 500 | 404 | 302 | 304 |
服务器收到请求,需要请求者继续执行操作 | 重定向 | 客户端请求的语法错误,服务器无法理解 | 内部服务器错误 | 資源未修改 |
3. responseType:
Json | document | blob | text | arraybuffer |
4. timeout