Files
ClassContent/历届学生/zheng-yuqing/项目练习/上课项目/ajax案例/ajax.js
2024-09-27 02:06:13 +08:00

60 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class AJAX {
constructor() {
// 请求基地址
// this.baseUrl = "http://127.0.0.1:3000/api/json";
this.baseUrl = "http://127.0.0.1:3000/api";
this.http = new XMLHttpRequest();
}
/**
*
* @param {*object} parmas
* {
* url: '', // 请求地址
* data : { page: 1, count: 15 } // 请求参数
* success: () => {} // ajax成功后回调拿回请求结果
* error: () => {} // ajax 失败后,回调拿回错误结果
* }
*/
get(parmas) {
// 将data 参数转化为 ?key=value&key=value
var str = ""
for (const key in parmas.data) {
str += `&${key}=${parmas.data[key]}`
}
str = str.replace("&", "?")
this.http.open("GET", `${this.baseUrl}${parmas.url}${str}`);
this.http.send();
this.readyState(parmas.success, parmas.error)
}
post(parmas) {
this.http.open("POST", `${this.baseUrl}${parmas.url}`);
this.http.setRequestHeader('Content-type', 'application/json; charset="utf-8"');
this.http.send(JSON.stringify(parmas.data));
this.readyState(parmas.success, parmas.error)
}
put() { }
delete() { }
// 给 get post put delete 进行状态监听的封装
readyState(success, error) {
this.http.onreadystatechange = () => {
if (this.http.readyState == 4) {
if (this.http.status == 200) {
var data = JSON.parse(this.http.response);
success(data)
} else {
error(this.http)
}
}
}
}
}
var http = new AJAX();