概述
XMLHttpRequest.readyState 属性返回一个 XMLHttpRequest 代理当前所处的状态。一个 XHR 代理总是处于下列状态中的一个:
| readyState | 状态描述 | 状态描述 | 
|---|---|---|
| 0 | UNSEND | 代理对象已经被创建,但尚未调用open()方法 | 
| 1 | OPENED | open()方法已经调用,建立与服务端口特定的链接 | 
| 2 | HEADERS_RECEIVED | send()方法已经被调用,并获得了状态行和响应头 | 
| 3 | LOADING | 响应体下载中,可能已经下载部分数据了 | 
| 4 | DONE | 响应体下载完成,可以直接使用responseText | 
代码–代理对象的状态

 准备一个后台文件json字符串,通过前后台交互理解readyState
- 状态为0
 
	var xhr = new XMLHttpRequest();console.log(xhr.readyState) //0//创建XHR,即请求初始化
 
- 状态为1
后台的文件这里是data.php 
	xhr.open('get','data.php')console.log(xhr.readyState) //1// 调用open()方法,建立与服务器端口的特定链接
 
- 状态为2
 
xhr.send()xhr.addEventListener('readystatechange', function(){switch(xhr.readyState){case 2:console.log(this.readyState)  //2//send()方法已经调用,可以拿到响应头了console.log(this.responseText)  //此时尚未拿到console.log(this.getAllResponseHeaders())
//date: Fri, 28 Dec 2018 02:28:34 GMT
//server: Apache/2.2.21 (Win32) PHP/5.3.10
//connection: Keep-Alive
//x-powered-by: PHP/5.3.10
//content-length: 380
//keep-alive: timeout=5, max=99
//content-type: text/htmlbreak;}})
 

- 状态为3
 
			case 3:console.log(this.readyState)  //3console.log(this.responseText)  //拿到响应体,可能是不完整的break;
 
看一下拿到的json
 
 后面很明显是断开了,是不完整;数据少,网速快等等,也有可能是完整,所以测试可以调一下慢网速看看
- 状态为4
 
case 4:console.log(this.readyState)  //4console.log(this.responseText)  //响应体下载完成,responseText可以使用console.log(document.readyState)var obj = JSON.parse(this.responseText)break;
 

 最后拿到的数据是完整的
使用我们JSON.parse转换成对象使用
console.log(obj)
 














