first commit

This commit is contained in:
编码猿
2024-09-27 02:06:13 +08:00
commit 852d94fbb9
36760 changed files with 3274413 additions and 0 deletions

View File

@@ -0,0 +1,70 @@
class ajax {
constructor() { // 类的参数初始化
this.baseUrl = "http://127.0.0.1:8090/api";
this.xhr = new XMLHttpRequest();
}
/**
*
* @param {*} params
* {
* url: 'http://127.0.0.1:3000/api/index/threeMeals',
* data: {
* page: 1,
* id: 1
* },
* success: function() {}
* }
*/
get(params) {
// 判断你传的参数里面是否有 data,没有的话就报错提示你
if (params.hasOwnProperty("data")) {
var str = ""
// 将 object 类型的 data 转为为 ?key=value&key=value
for (const key in params.data) {
str += `&${key}=${params.data[key]}`
}
str = str.replace("&", "?")
// 设置请求地址
this.xhr.open("GET", `${this.baseUrl}${params.url}${str}`)
//
this.xhr.send();
// 状态监听
this.onreadystatechange(params.success)
} else {
throw new Error("data参数必传")
}
}
onreadystatechange(callback) {
// this 指向
// 如何解决 this 指向
// 提前保存this
// 箭头函数 es6 es5
// bind
// var self = this;
this.xhr.onreadystatechange = () => {
if (this.xhr.readyState == 4) {
if (this.xhr.status == 200) {
callback(JSON.parse(this.xhr.response))
} else {
alert("网络请求错误")
}
}
}
}
}
var http = new ajax();