注意:只是简单封装,并没有考虑过多返回值类型,不支持请求头等
import queryString from 'query-string';
function myAajx(option={}) {
const defaults = {
url: "",
method: "get",
data: null,
};
option=Object.assign(defaults, option);
option.data=queryString.stringify(option.data); // x-www-from
let isGet=/^(GET|DELETE|OPTIONS|HEAD)/i.test(option.method);
if(isGet&&option.data){
const beforeUrl=option.url.includes('?')?`${option.url}?`:`${option.url}&`;
option.url+=`${beforeUrl}${option.data}`;
option.data=null; // 方便处理,不再将data传入请求体中send发送。
}
let ajax = new XMLHttpRequest();
return new Promise((res, rej)=>{
ajax.open(option.method, option.url);
ajax.onreadystatechange = function () {
if(!/^2d{2}/i.test(ajax.state)){
rej(ajax);
return ;
}
if (ajax.readyState === 4) {
const result=ajax.responseText;
res(result);
}
};
ajax.send(option.data);
});
}