封装Ajax-2、封装Ajax-3
封装Ajax-2
在地址上添加数据
addParam(){
const{ params } = this.options;
if(!params)return;
}
export default Ajax;
工具函数
const serialize = param =>{
const results = [];
for(const[ key,value ] of Object.entries(param)){
results.push(' ${encodeURlComponent(Key)} = $(encodeURlComponent(value)) ');
}
return results.join(' & ');
}
给URL添加参数
const addURLData =(url,data)=>{
if(!data)return;
conts mark = url.includes(' ?')?' & ':' ? ';
return ' ${mark}${data} ';
};
export{
serialize
};
封装Ajax-3
设置跨域是否携带cookie
setCookie(){
if(this.options.withCredentials){
this.xhr.withCredentials = true;
}
}
设置超时
setTimeout(){
const{ timeoutTime } = this.options;
if(timeoutTime > 0){
this.xhr.timeout = timeoutTime;
}
}
发送请求
sendDate(){
const xhr = this.xhr;
if(!this.isSendDate()){
return xhr.send(null);
}
}
是否需要使用send发送数据
isSendDate(){
const{date,method} = this.options;
if(!date){
return false;
}
if(method.toLowerCase() === ' HTTP_GET'.toLowerCase()){
return false;
}
}