first commit
This commit is contained in:
57
js/http/index.js
Normal file
57
js/http/index.js
Normal file
@@ -0,0 +1,57 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user