48 lines
1.2 KiB
JavaScript
48 lines
1.2 KiB
JavaScript
class Ajax {
|
|
|
|
// url 接口地址
|
|
// 请求参数
|
|
// 请求方法
|
|
// 请求成功的回调
|
|
// 请求失败的回调
|
|
|
|
http = new XMLHttpRequest();
|
|
constructor () {
|
|
}
|
|
|
|
//http://127.0.0.1:3000/api/json/index ?id=1&page=2
|
|
get(option) {
|
|
var params = ""
|
|
for (const key in option.data) {
|
|
params+= `&${key}=${option.data[key]}`
|
|
}
|
|
params = params.replace("&", "?")
|
|
option.url = option.url + params
|
|
|
|
this.http.open("GET", option.url);
|
|
this.http.send()
|
|
this.onreadystatechange(option)
|
|
}
|
|
|
|
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(callback) {
|
|
this.http.onreadystatechange = () => {
|
|
if (this.http.readyState == 4) {
|
|
if (this.http.status == 200) {
|
|
callback.success(JSON.parse(this.http.response))
|
|
} else {
|
|
callback.error(this.http)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
var ajax = new Ajax() |