59 lines
1.5 KiB
JavaScript
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)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|