Files
xiezheng_h5/js/http/index.js
2024-11-30 22:40:02 +08:00

57 lines
1.6 KiB
JavaScript

class Ajax {
xhr = new XMLHttpRequest()
get(option) {
return new Promise((success, error) => {
var params = ""
for (const key in option.data) {
params += `&${key}=${option.data[key]}`
}
params = params.replace("&", "?")
// option.url == /home/hot?id=1
this.xhr.open("GET", `${config.checkUrl()}${option.url}${params}`)
this.xhr.send()
this.stateChange(success, error)
})
}
post(option) {
return new Promise((success, error) => {
this.xhr.open("POST", option.url)
this.xhr.setRequestHeader("Content-Type", "application/json")
// post 参数在请求体(body)中发送
this.xhr.send(JSON.stringify(option.data))
this.stateChange(success, error)
})
}
stateChange(suc, err) {
this.xhr.onreadystatechange = () => {
if (this.xhr.readyState == 4) {
if (this.xhr.status == 200) {
let res = JSON.parse(this.xhr.response)
switch (res.status) {
case 200:
suc(res.data)
break;
case 404:
alert(res.message)
err(this.xhr)
break;
default:
break;
}
suc()
} else {
err(this.xhr)
}
}
}
}
}