class AJAX { constructor() { this.baseUrl = config.checkBaseUrl(); this.http = new XMLHttpRequest(); } /** * * @param {*object} parmas */ get(parmas) { return new Promise((success, error) => { // 将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(success, 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); switch (data.status) { case 200: success(data.result) break; case 404: alert(data.message) throw new Error(data.message) break; } // success(data) } else { error(this.http) } } } } } var http = new AJAX();