// Ajax封装函数
ajax = (type, url, data, success, failed)=> {
// 创建ajax对象
// eslint-disable-next-line no-undef
const xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft,XMLHTTP")
// 用于清除缓存
const random = Math.random();
if(type.toUpperCase() == 'GET'){
if(data){
xhr.open('GET', `${url}?${data}`, true);
} else {
xhr.open('GET', `${url}?t=${random}`, true);
}
if(typeof data === 'object'){
let str = '';
// eslint-disable-next-line no-restricted-syntax
for(const key in data){
str += `${key}=${data[key]}&`;
}
data = str.replace(/&$/, '');
}
xhr.send();
} else if(type.toUpperCase() == 'POST'){
xhr.open('POST', url, true);
if(data instanceof FormData) {
}else if(typeof data === 'object'){
let str = '';
// eslint-disable-next-line no-restricted-syntax
for(const key in data){
str += `${key}=${data[key]}&`;
}
data = str.replace(/&$/, '');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
xhr.send(data);
}
// 处理返回数据
xhr.onreadystatechange = ()=> {
if(xhr.readyState == 4){
/*
** Http状态码
** 1xx :信息展示
** 2xx :成功
** 3xx :重定向
** 4xx : 客户端错误
** 5xx :服务器端错误
*/
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
success(JSON.parse(xhr.responseText))
} else if(failed){
failed(xhr.status)
}
}
}
}
网友评论