Files
ClassContent/历届学生/front-end-team-10/项目练习/学生项目/薛涛/3.8/js/http/index.js
2024-09-27 02:06:13 +08:00

59 lines
1.5 KiB
JavaScript

class Http {
constructor() {
this.xhr = new XMLHttpRequest();
}
get(params) {
return new Promise((success, error) => {
var par = ""
for (const key in params.data) {
par += `&${key}=${params.data[key]}`
}
par = par.replace("&", "?")
this.xhr.open("GET", `${config.switchStage()}${params.url}${par}`)
this.xhr.send()
this.ReadyState(success, error)
})
}
post(params) {
return new Promise((success, error) => {
this.xhr.open("POST", `${params.url}`)
this.xhr.setRequestHeader('Content-Type', 'application/json');
this.xhr.send(JSON.stringify(params.data))
this.ReadyState(success, error)
})
}
ReadyState(success, error) {
this.xhr.onreadystatechange = () => {
if (this.xhr.readyState == 4) {
if (this.xhr.status == 200) {
var data = JSON.parse(this.xhr.response);
switch (data.status) {
case 200:
success(data.result)
break;
case 404:
alert(data.msg)
throw new Error(data.msg)
break;
default:
break;
}
} else {
error(this.xhr)
}
}
}
}
}