67 lines
1.8 KiB
JavaScript
67 lines
1.8 KiB
JavaScript
class Http {
|
|
defaultOption = {
|
|
timeout: 6000,
|
|
headers: {
|
|
'Content-Type': 'application/json;charset=utf-8'
|
|
}
|
|
}
|
|
|
|
constructor() {
|
|
this.xhr = new XMLHttpRequest()
|
|
}
|
|
|
|
get(par) {
|
|
return new Promise((success, error) => {
|
|
this.setOption(par)
|
|
let urlParams = ""
|
|
for (const key in par.data) {
|
|
urlParams += `&${key}=${par.data[key]}`
|
|
}
|
|
urlParams = urlParams.replace("&", "")
|
|
this.xhr.open("GET", `${par.url}?${urlParams}`)
|
|
this.xhr.timeout = this.defaultOption.timeout
|
|
this.setHeader(par.headers)
|
|
this.xhr.send()
|
|
this.statechange(success, error);
|
|
})
|
|
}
|
|
|
|
post(par) {
|
|
return new Promise((success, error) => {
|
|
this.setOption(par)
|
|
this.xhr.open("POST", par.url)
|
|
this.xhr.timeout = this.defaultOption.timeout
|
|
this.setHeader(par.headers)
|
|
this.xhr.send(JSON.stringify(par.data))
|
|
this.statechange(success, error);
|
|
})
|
|
}
|
|
|
|
setOption(par) {
|
|
this.defaultOption.timeout = par.timeout || this.defaultOption.timeout
|
|
// ....
|
|
}
|
|
|
|
setHeader(headerObject = {}) {
|
|
Object.assign(headerObject, this.defaultOption.headers)
|
|
for (const key in headerObject) {
|
|
this.xhr.setRequestHeader(key, headerObject[key]);
|
|
}
|
|
}
|
|
|
|
statechange(success, error) {
|
|
this.xhr.onreadystatechange = () => {
|
|
if (this.xhr.readyState == 4) {
|
|
if (this.xhr.status == 200) {
|
|
let data = JSON.parse(this.xhr.response)
|
|
success(data)
|
|
} else {
|
|
error(this.xhr)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
var http = new Http();
|