AJAX (Async JavaScript And XML)
AJAX 封装
ajax({
url:' https://www.easy-mock.com/mock/5c3d540995b2d32cb1e95970/test/subAccount/confirmFreeze.do',
type:'get',// get post 默认的话是get
data:{a:12},// 传输给后台的数据
dataType:'json',// json xml;默认 json
cache:true,// 是否缓存
async:true,// 是否异步
success:function(data){
console.log(data);
},
error:function(err){
console.log(err);
}
});
===================================================
promiseAjax封装
ajax({
url:'https://www.souyidai.com/?suc=103120100&sut=101',
type:'get',
data:{a:12},
dataType:'json',// json xml;默认 json
cache:false,
async:true,// 是否异步
}).then((data)=>{
console.log(data);
},(err)=>{
console.log(err);
})
function ajax(options){
let{
url,
type = 'get',// 给 type一个备用值
data,
dataType = 'json',
cache = true,// 默认走缓存 处理get的缓存问题
async = true,// 默认异步
success,// 成功的回调函数
error // 失败的回掉函数
} = options;
let str = '';
for(let k in data){
str += `${k}=${encodeURIComponent(data[k])}&`;
}
str = str.slice(0,str.length-1);// 去出最后面的 &
let isGet = /^(get|head|datele)$/.test(type);// isGet 就是 test 的返回值
// 若是get
if(isGet){
let ary = url.split('?');
if(ary[1] === ''){
url += str;
}else if(ary[1] === undefined){
url += '?' + str;
}else{
/&$/.test(ary[1]) ? url += str : url += '&' + str;
}
if(!cache){
// 不走缓存
url += `&_${Date.now()}`;
}
}
return new Promise((res,rej)=>{
let xhr = new XMLHttpRequest();
xhr.open(type,url,true);
xhr.onreadystatechange =function(){
if(xhr.responseText == 4){
if(/^{2\d{2}|304}$/.test(xhr.status)){
let data = JSON.parse(xhr.responseText);
res(data);
}else{
rej(xhr);
}
}
}
// 设置请求头 把数据以 Form Data的形式传给后台
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send(str);
})
}