Files
ClassContent/历届学生/fontendsix/项目练习/上课项目/屁桃儿/js/ajax/index.js
2024-09-27 02:06:13 +08:00

105 lines
2.7 KiB
JavaScript

class AjAX {
constructor() {
this.xhr = new XMLHttpRequest();
}
/**
*
* @param {*} params
* url: 字符串 请求地址,
* data: 对象
*/
get(params) {
return new Promise((success, error) => {
var record = ""
for (const key in params.data) {
record += `&${key}=${params.data[key]}`
}
record = record.replace("&", "?")
console.log(`${config.checkStage()}${params.url}${record}`);
this.xhr.open("GET", `${config.checkStage()}${params.url}${record}`)
this.xhr.send();
this.readystatechange(success, error)
})
}
post(params) {
console.log(params);
return new Promise((success, error) => {
this.xhr.open("POST", `${config.checkStage()}${params.url}`)
this.xhr.setRequestHeader("Content-type","application/json");
this.xhr.send(JSON.stringify(params.data));
this.readystatechange(success, error)
})
}
readystatechange(success, error) {
this.xhr.onreadystatechange = () => {
if (this.xhr.readyState == 4) {
if (this.xhr.status == 200) {
var res = JSON.parse(this.xhr.responseText);
// 业务逻辑状态码的判断
switch (res.status) {
case 200:
success(res.result || res.data)
break;
case 404:
alert(res.message)
throw new Error(res.message)
break;
default:
break;
}
} else {
error(this.xhr)
}
}
}
}
}
// a.get({
// url: '/index/class',
// data: {
// type: 1,
// page: 1
// },
// success: (res) => {
// console.log("拿到的数据为:", res);
// },
// error: (err) => {
// console.log("请求出错了:", err);
// }
// });
// function test() {
// return new Promise(function (success, error) {
// var a = 1
// setTimeout(() => {
// a += 1;
// success(a)
// }, 3000)
// })
// }
// var dd = async () => {
// // test()
// // .then((res) => {
// // console.log(res);
// // })
// // .catch()
// var num = await test();
// console.log(num);
// }
// dd()
// 回调地狱
// 异步返回值 回调 promise
// 系统级别判断
// await indexService.class({ type: 1, page: 1 })