Files
ClassContent/历届学生/front-end-team-10/项目练习/学生项目/韩孟雪/2023-3-3/ajaxV2.js
2024-09-27 02:06:13 +08:00

48 lines
1.2 KiB
JavaScript

class Http {
constructor() {
this.xhr = new XMLHttpRequest();
}
//获取地址栏参数 异步代码
get(params) {
return new Promise((success, error) => {
var par = ""
for (const key in params.data) {
par += `&${key}=${params.data[key]}`
}
par = par.replace("&", "?")
this.xhr.open("GET", `${params.url}${par}`)
this.xhr.send()
this.ReadyState(success, error)
})
}
//数据请求方式
post(params) {
return new Promise((success, error) => {
this.xhr.open("POST", `${params.url}`)
this.xhr.setRequestHeader('Content-Type', 'application/json');
this.xhr.send(JSON.stringify(params.data))
this.ReadyState(success, error)
})
}
ReadyState(success, error) {
this.xhr.onreadystatechange = () => {
if (this.xhr.status == 4) {
if (this. xhr.status == 200) {
var data = JSON.parse(this.xhr.response);
success(data)
} else {
error(this. xhr)
}
}
}
}
}
var http = new Http();