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();