class Http { constructor() { this.xhr = new XMLHttpRequest(); } /** * url : 请求地址 */ 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}`) // POST 一般发送两种格式的数据 // 表单类型 FormData 数据格式 name=value&name=value // json数据类型 数据格式就是 JSON.stringify() 后的字符串对象 // json 用的多 // var par = "" // for (const key in params.data) { // par += `&${key}=${params.data[key]}` // } // par = par.replace("&", "") 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.readyState == 4) { if (this.xhr.status == 200) { var data = JSON.parse(this.xhr.response); success(data) } else { error(this.xhr) } } } } } var http = new Http();