摘自千峰教育kerwin的js教程
const xhr = new XMLHttpRequest();
// xhr 对象中的 open 方法是来配置请求信息的
// 第一个参数是本次请求的请求方式 get / post / put / ...
// 第二个参数是本次请求的 url
// 第三个参数是本次请求是否异步,默认 true 表示异步,false 表示同步
// xhr.open('请求方式', '请求地址', 是否异步)
xhr.open('get', './data.php')
// 使用 xhr 对象中的 send 方法来发送请求
xhr.send()
xhr.readyState
readyState === 0
: 表示未初始化完成,也就是 open
方法还没有执行readyState === 1
: 表示配置信息已经完成,也就是执行完 open
之后readyState === 2
: 表示 send
方法已经执行完成readyState === 3
: 表示正在解析响应内容readyState === 4
: 表示响应内容已经解析完毕,可以在客户端使用了readyState === 4
的时候,我们才可以正常使用服务端给我们的数据xhr.status
在 ajax 对象中有一个事件,叫做 readyStateChange
事件
这个事件是专门用来监听 ajax 对象的 readyState
值改变的的行为
也就是说只要 readyState
的值发生变化了,那么就会触发该事件(所以响应过程会触发多次)
所以我们就在这个事件中来监听 ajax 的 readyState
是不是到 4 了
const xhr = new XMLHttpRequest()
xhr.open('get', './data.php')
xhr.send()
xhr.onreadyStateChange = function () {
// 每次 readyState 改变的时候都会触发该事件
// 我们就在这里判断 readyState 的值是不是到 4
// 并且 http 的状态码是不是 200 ~ 299
if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
// 这里表示验证通过
// 我们就可以获取服务端给我们响应的内容了
}
}
xhr.readyState === 4
时才会触发xhr.onload = function () {
if (xhr.status == 200) {
} else of (xhr.status == 404) {
}
}
ajax 对象中的 responseText
成员
就是用来记录服务端给我们的响应体内容的
所以我们就用这个成员来获取响应体内容就可以
const xhr = new XMLHttpRequest()
xhr.open('get', './data.php')
xhr.send()
xhr.onreadyStateChange = function () {
if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
// 我们在这里直接打印 xhr.responseText 来查看服务端给我们返回的内容
console.log(xhr.responseText)
}
}
const xhr = new XMLHttpRequest()
// 直接在地址后面加一个 ?,然后以 key=value 的形式传递
// 两个数据之间以 & 分割
xhr.open('get', './data.php?a=100&b=200')
xhr.send()
const xhr = new XMLHttpRequest()
xhr.open('get', './data.php')
// 如果是用 ajax 对象发送 post 请求,必须要先设置一下请求头中的 content-type
// 告诉一下服务端我给你的是一个什么样子的数据格式
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
// 请求体直接再 send 的时候写在 () 里面就行
// 不需要问号,直接就是 'key=value&key=value' 的形式
xhr.send('a=100&b=200')
application/x-www-form-urlencoded
表示的数据格式就是 key=value&key=value
function queryStringify(obj) {
let str = ''
for (let k in obj) str += `${k}=${obj[k]}&`
return str.slice(0, -1)
}
// 封装 ajax
function ajax(options) {
let defaultoptions = {
url: "",
method: "GET",
async: true,
data: {},
headers: {},
success: function () { },
error: function () { }
}
// 默认值合并,保证所有参数都有效
let { url, method, async, data, headers, success, error } = {
...defaultoptions,
...options
}
// 当传的是对象,且设置header也是json时,将传的对象{key:value}转化为json
if (typeof data === 'object' && headers["content-type"]?.indexOf("json") > -1) {
data = JSON.stringify(data)
}
else {
// 以下情况需要处理
// 1. 传的是对象,但是header设置的xxx-form-urlencoded
// 2. 传的直接就是表单(不设置的话默认是form编码) name=123&age=10
data = queryStringify(data)
}
// 如果是 get 请求, 并且有参数, 那么直接组装一下 url 信息
if (/^get$/i.test(method) && data) url += '?' + data
// 4. 发送请求
const xhr = new XMLHttpRequest()
xhr.open(method, url, async)
xhr.onload = function () {
if (!/^2\d{2}$/.test(xhr.status)) {
error(`错误状态码:${xhr.status}`)
return
}
// 执行解析
try {
let result = JSON.parse(xhr.responseText)
success(result)
} catch (err) {
error('解析失败 ! 因为后端返回的结果不是 json 格式字符串')
}
}
// 设置请求头内的信息
for (let k in headers) xhr.setRequestHeader(k, headers[k])
if (/^get$/i.test(method)) {
xhr.send()
} else {
xhr.send(data)
}
}
ajax({
url:"http://localhost:3000/users",
method:"GET",
async:true,
// 这里header默认是form编码,但是传的对象,所以走else逻辑
data:{
username:"kerwin",
password:"123"
},
headers:{},
success:function(res){
console.log(res)
},
error:function(err){
console.log(err)
}
})
当一个回调函数嵌套一个回调函数的时候
就会出现一个嵌套结构
当嵌套的多了就会出现回调地狱的情况
比如我们发送三个 ajax 请求
第一个正常发送
第二个请求需要第一个请求的结果中的某一个值作为参数
第三个请求需要第二个请求的结果中的某一个值作为参数
ajax({
url: '我是第一个请求',
success (res) {
// 现在发送第二个请求
ajax({
url: '我是第二个请求',
data: { a: res.a, b: res.b },
success (res2) {
// 进行第三个请求
ajax({
url: '我是第三个请求',
data: { a: res2.a, b: res2.b },
success (res3) {
console.log(res3)
}
})
}
})
}
})
promise
是一个 ES6 的语法
承诺的意思,是一个专门用来解决异步 回调地狱 的问题
语法:
new Promise(function (resolve, reject) {
// resolve 表示成功的回调
// reject 表示失败的回调
}).then(function (res) {
// 成功的函数
}).catch(function (err) {
// 失败的函数
})
promise 就是一个语法
我们的每一个异步事件,在执行的时候
都会有三个状态,执行中 / 成功 / 失败
因为它包含了成功的回调函数
所以我们就可以使用 promise 来解决多个 ajax 发送的问题
new Promise(function (resolve, reject) {
ajax({
url: '第一个请求',
success (res) {
resolve(res)
}
})
}).then(function (res) {
// 准备发送第二个请求
return new Promise(function (resolve, reject) {
ajax({
url: '第二个请求',
data: { a: res.a, b: res.b },
success (res) {
resolve(res)
}
})
})
}).then(function (res) {
ajax({
url: '第三个请求',
data: { a: res.a, b: res.b },
success (res) {
console.log(res)
}
})
})
async/await
是一个 es7 的语法
这个语法是 回调地狱的终极解决方案
语法:
async function fn() {
const res = await promise对象
}
可以把异步代码写的看起来像同步代码
只要是一个 promiser 对象,那么我们就可以使用 async/await
来书写
async function fn() {
const res = await new Promise(function (resolve, reject) {
ajax({
url: '第一个地址',
success (res) {
resolve(res)
}
})
})
// res 就可以得到请求的结果
const res2 = await new Promise(function (resolve, reject) {
ajax({
url: '第二个地址',
data: { a: res.a, b: res.b },
success (res) {
resolve(res)
}
})
})
const res3 = await new Promise(function (resolve, reject) {
ajax({
url: '第三个地址',
data: { a: res2.a, b: res2.b },
success (res) {
resolve(res)
}
})
})
// res3 就是我们要的结果
console.log(res3)
}
这种方式如果要捕获错误,可以使用try-catch方式
XMLHttpRequest 是一个设计粗糙的 API,配置和调用方式非常混乱, 而且基于事件的异步模型写起来不友好。
兼容性不好 polyfill: https://github.com/camsong/fetch-ie8,所以还是推荐封装ajax
fetch("http://localhost:3000/users")
.then(res=>res.json())
.then(res=>{
console.log(res)
})
fetch("http://localhost:3000/users",{
method:"POST",
headers:{
"content-type":"application/json"
},
body:JSON.stringify({
username:"kerwin",
password:"123"
})
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
fetch("http://localhost:3000/users/5",{
method:"PUT",
headers:{
"content-type":"application/json"
},
body:JSON.stringify({
username:"kerwin",
password:"456"
})
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
fetch("http://localhost:3000/users/5",{
method:"DELETE"
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
//错误处理
fetch("http://localhost:3000/users1")
.then(res=>{
if(res.ok){
return res.json()
}else{
// 手动拒绝
return Promise.reject({
status:res.status,
statusText:res.statusText
})
}
})
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})
我写过的基于React的项目中,一般会使用将axios(另个一将xhr封装的npm包)二次封装的方式,结合框架进行使用。