// 原生ajax->调用后台接口(网址、提供数据操作)
// 理解 axios 原生ajax+Promise
let count = 0
function ajax(method, url) {
count++
// 1 创建xhr对象
const xhr = new XMLHttpRequest()
// 2 配置 第一个 请求方法 第二个 请求路径 (接口文档)
xhr.open(method, url)
// 3 监听事件
// 请求过程中,状态发生变化就触发
xhr.onreadystatechange = function () {
// console.log(111)
// console.log(xhr.status) // 200 成功
// console.log(xhr.readyState) // 4 请求回来
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText) // 拿到服务器响应内容
if (count === 2) return
ajax('GET', 'http://127.0.0.1:5173/list')
}
}
}
// 4 发送
xhr.send()
}
ajax('GET', 'http://127.0.0.1:5173/list')
console.log('end')
// 原生ajax->调用后台接口(网址、提供数据操作)
// 理解 axios 原生ajax+Promise
function ajaxPromise(url) {
return new Promise((resolve, reject) => {
// ajax代码
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.addEventListener('loadend', function () {
if (xhr.status >= 200 && xhr.status < 300) {
// 请求成功
resolve(xhr.response)
} else {
reject(new Error('请求失败'))
}
})
xhr.send()
})
}
//const p = ajaxPromise()
/* 获取所有省->获取所有市
ajaxPromise('http://127.0.0.1:5173/list')
.then(
(data) => {
console.log('success', data)
return ajaxPromise('http://127.0.0.1:5173/list')
},
(err) => {
console.log(err)
}
)
.then((data) => {
console.log('data11111', data)
return ajaxPromise('http://127.0.0.1:5173/list')
})
.then((data) => {
console.log('data2222', data)
})
*/
async function getData() {
// await 代替then提取Promise成功状态的结果
// await后面的promise实例报错,可以用try catch捕获
try {
const data1 = await ajaxPromise('https://127.0.0.1:5173/list')
console.log('-------', data1)
const data2 = await ajaxPromise('http://127.0.0.1:5173/list')
console.log('-------', data2)
const data3 = await ajaxPromise('http://127.0.0.1:5173/list')
console.log('-------', data3)
} catch (e) {
console.dir(e)
}
}
getData()
// async 和 await
// await 配合async使用 代替then