// get /data/test.jsonconst xhr = new XMLHttpRequest()xhr.open("GET", "/data/test.json", true) // true 异步请求xhr.onreadystatechange = function () { if(xhr.readyState === 4) { if(xhr.status === 200) { console.log( JSON.parse(xhr.responseText) ) alert(xhr.responseText) } }}xhr.send(null)
// postconst xhr = new XMLHttpRequest()xhr.open("POST", "/login", true) // true 异步请求xhr.onreadystatechange = function () { if(xhr.readyState === 4) { if(xhr.status === 200) { console.log( JSON.parse(xhr.responseText) ) alert(xhr.responseText) } }}const postData = { userName: 'zhangsan', password: 'xx'}xhr.send(JSON.stringify(postData))
xhr.readyState
- 0- (未初始化)还没有调用send()方法
- 1-(载入)已调用send()方法,正在发送请求
- 2-(载入完成)send()方法执行完成,已经接收到全部相应内容
- 3- (交互)正在解析响应内容
4- (完成)响应内容解析完成,可以在客户端调用
xhr.status
2xx- 表示请求成功,如200
- 3xx- 表示重定向, 浏览器直接跳转,如301 302 304
- 4xx- 表示客户端请求错误, 如403 404
- 5xx- 表示服务端错误