Files
ClassContent/历届学生/吴欣阳/项目开发/上课项目/美食app/front/js/ajax/ajax.js
2024-09-27 02:06:13 +08:00

75 lines
1.6 KiB
JavaScript

class Ajax {
constructor () {
this.http = new XMLHttpRequest();
}
get(option) {
Tips.loading()
var params = ""
for (const key in option.data) {
params+= `&${key}=${option.data[key]}`
}
params = params.replace("&", "?")
option.url = this.url() + option.url + params
return new Promise( (resolve, reject) => {
this.http.open("GET", option.url);
this.http.send()
return this.onreadystatechange(resolve, reject)
})
}
post(option) {
this.http.open("POST", option.url);
this.http.setRequestHeader('Content-Type', 'application/josn');
this.http.send(JSON.stringify(option.data))
this.onreadystatechange(option)
}
onreadystatechange(resolve, reject) {
this.http.onreadystatechange = () => {
if (this.http.readyState == 4) {
Tips.close()
if (this.http.status == 200) {
var res = JSON.parse(this.http.response);
switch (res.status) {
case 200:
resolve(res.result);
break;
case 404:
Tips.dialog({
title: '程序出错啦',
message: res.msg
});
throw new Error(res.msg);
break;
}
resolve()
} else {
reject(this.http)
}
}
}
}
url() {
switch (config.stage) {
case "dev":
return config.devUrl;
break;
case "test":
return config.testUrl;
break;
case "prod":
return config.prodUrl;
break;
}
}
}
var ajax = new Ajax()