Files
2024-09-27 02:06:13 +08:00

70 lines
1.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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();