使用promise封装ajax
直接上代码:
1 function Ajax(method, headers, url, data, progress = null) { 2 return new Promise(function (resolve, reject) { 3 let xhr = new XMLHttpRequest(); 4 xhr.open(method,url);//配置 5 for (const key in headers) {//遍历header,设置响应头 6 let value = headers[key]; 7 xhr.setRequestHeader(key,value); 8 } 9 xhr.send(data);//发送,并配置响应体 10 xhr.onreadystatechange = function () { 11 if (xhr.readyState === 4) { 12 try {//设置了超时时间, 防止由于该条件(即readystate等于4)成立, 进入该判断块, 下面的status读取不到, 导致抛出错误 13 if (xhr.status >= 200 || xhr.status < 300 || xhr.status == 304) { 14 resolve(xhr.responseText); 15 } else { 16 reject(new Error(xhr.statusText)); 17 } 18 } catch (error) { 19 reject(new Error('服务器错误请重试')); 20 } 21 } 22 }; 23 }); 24 }