utils.js:
//工具函数
//数据序列化成urlencoded格式的字符串
const serialize=param=>{
const results=[];
for(const [key,value] of Object.entries
(param)){
results.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
}
// ['username=alex','age=18' ]
return results.join('&')
};
//数据序列化成JSON格式的字符串
const serializeJSON=param=>{
return JSON.stringify(param)
}
//给URL添加参数
//www.imooc.com?words=js&
const addURLData=(url,data)=>{
if(!data)return '';
const mark=url.includes('?')?'&':'?';
return `${mark}${data}`;
};
export{serialize,addURLData,serializeJSON}
constants.js:
//常量
export const HTTP_GET='GET';
export const CONTENT_TYPE_FORM_URLENCODED="application/x-www-form-urlencoded";
export const CONTENT_TYPE_JSON="application/json";
index.js:
import Ajax from './ajax.js';
const ajax=(url,options)=>{
return new Ajax(url,options).getXHR();
};
const get=(url,options)=>{
return ajax(url,{...options,method:'GET'});
};
const getJSON=(url,options)=>{
return ajax(url,{...options,method:'GET',responseType:'json'});
};
const post=(url,options)=>{
return ajax(url,{...options,method:'GET'});
}
export {ajax,get,getJSON,post};
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星