function ajax(options){
//适配参数
options = Object.assign({
url: '',
method: '',
data: '',
headers: {},
async: true
},options);
//适配data属性
if(typeof options.data !== "string"){
let str = '';
for(let key in options.data) {
str += `&${key} = ${options.data[key]}`;
}
options.data = str.slice(1);
}
if(options.method.toUpperCase() === 'GET') {
options.url += '?' + options.data;
}
return new Promise((resolve, reject) => {
let xhr;
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject) {
xhr = new ActiveXObject();
}else{
alert('浏览器版本过低')
return reject('浏览器不支持Ajax')
}
})
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status === 200 || xhr.status === 304) {
resolve(JSON.parse(xhr.responseText))
}else{
reject('请求失败')
}
}
}
xhr.open(options.method, options.url, options.async);
if(options.headers) {
for(let key in options.headers) {
xhr.setRequestHeader(key, options.headers[key])
}
}
xhr.send(options.data)
}
ajax({
url:'/send',
method: 'POST',
data:{data}
}).then(data => {
console.log(11)
})