直接上代码:

 function Ajax(method, headers, url, data, progress = null) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();   
xhr.open(method,url);//配置
for (const key in headers) {//遍历header,设置响应头
let value = headers[key];
xhr.setRequestHeader(key,value);
}
xhr.send(data);//发送,并配置响应体
xhr.onreadystatechange = function () {
if (xhr.readyState === ) {
try {//设置了超时时间, 防止由于该条件(即readystate等于4)成立, 进入该判断块, 下面的status读取不到, 导致抛出错误
if (xhr.status >= || xhr.status < || xhr.status == ) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
} catch (error) {
reject(new Error('服务器错误请重试'));
}
}
};
});
}
05-22 16:10