前言
知识点:
- XMLHttpRequest
- 状态码
- 跨域:同源策略,跨域解决方案
参考文档:developer.mozilla.org/zh-CN/docs/…
GET
// get请求
// xhr.open()第三个参数是一个可选的布尔参数,默认为true,表示要不要异步执行操作。
const xhr = new XMLHttpRequest()
xhr.open('GET','/api', false)
// onreadystatechange,当readystate变化的时候,类似于img.onload、img.onerror
xhr.onreadystatechange = function () {
// 这里的函数异步执行,可参考之前JS基础中的异步模块
// 细节:readyState为4
if (xhr.readyState === 4) {
// 返回成功状态码为200
if (xhr.status === 200) {
// 细节:转为对象
console.log(JSON.parse(xhr.responseText)
alert(xhr.responseText)
}
}
}
// 发送数据
xhr.send(null)
POST
// post
const xhr = new XMLHttpRequest()
xhr.open('POST', '/login', false)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
alert(xhr.responseText)
} else {
console.log('other')
}
}
}
const postData = {
userName: 'zhangsan',
password: 'xxx'
}
// 细节:要以字符串的形式发送数据,其它工具已经帮我们转成了字符串
xhr.send(JSON.stringify(postData)
xhr.readState状态码含义
- 0---(未初始化)还没有调用send()方法
- 1---(载入)已调用send()方法,正在发送请求
- 2---(载入完成)send()方法执行完成,已经接收到全部响应内容
- 3---(交互)正在解析响应内容
- 4---(完成)响应内容解析完成,可以在客户端调用
xhr.status表示http协议的状态码
- 2xx --- 表示成功处理请求,如 200
- 3xx --- 需要重定向,浏览器直接跳转,如 301:永久重定向, 302:临时重定向,304:资源未改变,浏览器用自身缓存的资源
- 4xx --- 客户端请求错误,如404:客户端请求错误,找不到 403:没有权限
- 5xx --- 服务端错误