当前位置: 首页 > Web前端 > HTML

问题40:如何实现一个ajax?

时间:2023-04-02 23:41:01 HTML

主要使用如下文件config.js:ajax请求配置核心文件loading.js:element-ui请求加载动画index.js:二次封装config.js请求并导出该方法,配置请求拦截器,响应拦截器index.vue:Sample调用ajax的页面注意:建议在api目录下管理所有接口。如果遇到错误,请调整正确的引用路径config.jsimportloadingfrom'./loading.js';//加载动画类constanimation=false;//界面加载动画constintTimer=10;//接口请求超时时间(秒)classConfig{constructor(data){this.method=data.method;this.url=data.url;this.param=data.param||{};this.header=data.header||{};this.interceptors=data.interceptors;this.response=data.response;返回this.filter();}//创建XHR对象createXHR(){if(window.XMLHttpRequest){//IE7+、Firefox、Chrome、Opera、Safari的代码returnnewXMLHttpRequest();}else{//针对IE6、IE5的代码returnnewActiveXObject('Microsoft.XMLHTTP');}}//HTTP请求xhrRequest(header,method,url,param,async,interceptors,response){returnnewPromise(resolve=>{varxhr=this.createXHR();if(animation==true){loading.requestStart();//执行动画}//请求拦截if(interceptors({header,method,url:this.url,param:this.param,async})){xhr.open(method,url,async);xhr.timeout=1000*intTimer;//设置xhr请求的超时时间Object.keys(header).map(key=>{xhr.setRequestHeader(key,header[key]);});xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;application/json;charset=utf-8');xhr.send(param);xhr.onreadystatechange=()=>{if(xhr.readyState==4&&xhr.status==200){loading.requestEnd();//结束动画尝试{letdata=JSON.parse(xhr.responseText);resolve(response(data,{header,method,url:this.url,param:this.param,async}));}catch(error){console.log('接口没有返回任何信息!');解决(假);}}else{return'请求不成功'+xhr.status;}};}else{console.error('请求拦截器','请求未发送,请求拦截器生效!');}//请求超时方法xhr.ontimeout=function(e){console.log('接口请求超时!');loading.requestEnd();//结束动画};//请求错误方法xhr.onerror=function(e){console.log('接口请求失败');loading.requestEnd();//结束动画};});}//参数转换convParams(param){letmark='?';让hasMark=this.url。索引(标记)>0;//是否包含带有特殊字符if(hasMark){mark='&';}让newParams='';让我=0;for(letkeyinparam){if(i>0){newParams+=`&${key}=${param[key]}`;}else{newParams+=`${mark}${key}=${param[key]}`;我++;}返回新参数;}//数据GET,POST请求Handlefilter(){letobj={header:this.header,method:this.method,url:this.url,param:{},async:true,interceptors:this.interceptors,响应:this.response};//接口名称拼接位置:(1,url)(2,param)letnewParams=this.convParams(this.param);if(this.method=='GET'){obj.url+=newParams;}else{newParams=newParams.replace('?','');obj.param=newParams;}返回this.xhrRequest(obj.header,obj.method,obj.url,obj.param,obj.async,obj.interceptors,obj.response);}}导出默认配置;loading.jsimport{Loading}from'element-ui';classanimation{constructor(){this.needLoadingRequestCount=0;this.loading}/***动画开始*/requestStart(){if(this.needLoadingRequestCount===0){this.loading=Loading.service({lock:true,text:'loading...',background:'rgba(0,0,0,0.7)'});}this.needLoadingRequestCount++;}/***动画绑定*/requestEnd(){if(this.needLoadingRequestCount<=0)return;this.needLoadingRequestCount--;如果(this.needLoadingRequestCount===0){this.loading.close();}}}exportdefaultnewanimation()index.jsimportConfigfrom'./config.js';/***接口请求方法*@funcrequest*@param{Object}method请请求方式:只支持GET、POST*@参数{String}url请求地址*@param{Object}param请求参数*/letrequest=option=>{//配置默认请求参数returnnewConfig({header:{Authorization:'APPCODEedc39cc1dc5f4c139498322115b99e51'},method:option.method,url:option.url,param:option.param,interceptors:拦截器,response:response});};/***请求拦截器*@func拦截器*/letinterceptors=config=>{returntrue;};/***响应拦截器*@funcresponse*/letresponse=(data,config)=>{letres;//处理返回格式if(data.res){res=data.res;}elseif(data.data){res=data.data;}else{res=数据;}returnres;};exportdefaultrequest;index.vue文章内容/灵感借鉴自以下内容【持续维护/更新500+前端面试题/笔记】https://github.com/noxussj/In...【大数据可视化图表插件】https://www.npmjs.com/package...【使用THREE.JS实现3D城市建模(珠海市)】https://3d.noxussj.top/