let axios = {
get (url, data) {
// data穿递参数需要拼接
if (data) {
let param = '?';
for (let attr in data) {
param += attr + '=' + data[attr] + '&';
console.log(attr)
}
url += param;
}
return this.request('get', url);
},
post (url, data) {
let param = '';
if (data) { //{id:1,info:22}
for (let attr in data) {
param += attr + '=' + data[attr] + '&';
}
// id=1&info=2
}
return this.request('post', url, param);
},
request (type, url, data) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(type, url);
// 判断是否为post请求
type == 'post' && xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(data);
// 监听ajax状态接收返回值
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) { // ajax的状态
if (xhr.status == 200) {
resolve(xhr.response) // 成功
} else {
reject(xhr.response); // 失败
}
}
}
})
}
};
// 获取节点的方法