61 lines
1.4 KiB
JavaScript
61 lines
1.4 KiB
JavaScript
(function (){
|
|
|
|
class Ajax {
|
|
|
|
constructor() {
|
|
this.ajax = new XMLHttpRequest();
|
|
}
|
|
|
|
get(option) {
|
|
var params = ""
|
|
for(var key in option.data) {
|
|
params+= `&${key}=${option.data[key]}`
|
|
}
|
|
params = params.replace("&", "?")
|
|
option.url = option.url + params
|
|
|
|
this.ajax.open("GET", option.url)
|
|
this.ajax.send()
|
|
this.readystatechange(option.success, option.error && option.error)
|
|
}
|
|
|
|
post(option) {
|
|
this.ajax.open("POST", option.url)
|
|
this.ajax.setRequestHeader("Content-Type","application/json")
|
|
this.ajax.send(JSON.stringify(option.data))
|
|
this.readystatechange(option.success, option.error && option.error)
|
|
}
|
|
|
|
readystatechange(success,error) {
|
|
this.ajax.onreadystatechange = () => {
|
|
if (this.ajax.readyState == 4) {
|
|
if (this.ajax.status == 200) {
|
|
|
|
var result = typeof this.ajax.responseText == "string"
|
|
? JSON.parse(this.ajax.responseText)
|
|
: this.ajax.responseText;
|
|
|
|
|
|
switch (result.status) {
|
|
case 200:
|
|
success(result.data)
|
|
break;
|
|
case 500:
|
|
error(result.msg)
|
|
break;
|
|
default:
|
|
}
|
|
|
|
|
|
} else {
|
|
error("请求出错")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
window.$ajax = new Ajax()
|
|
|
|
|
|
})() |