ajax拦截器 重复提交
发布时间:2020-12-16 03:29:24 所属栏目:百科 来源:网络整理
导读:/** * ajax拦截器,自带阻止多次提交解决方案 * */ var ajax = (function(){ let ajax = function(options){ let key = JSON.stringify(options); if( (options.avoidDuplicateRequesting || avoidDuplicateRequesting) ){ if(ajax.isRequestingInProgress(ke
/** * ajax拦截器,自带阻止多次提交解决方案 * */ var ajax = (function(){ let ajax = function(options){ let key = JSON.stringify(options); if( (options.avoidDuplicateRequesting || avoidDuplicateRequesting) ){ if(ajax.isRequestingInProgress(key)){ return ajax.addRequestingInProgress(key) } } return ajaxBase(options); }; let beforeSendInterceptors = [],//全局发送前拦截器 completeInterceptors = [],//全局发送后的拦截器 avoidDuplicateRequesting = false,//可以直接在全局修改他,这样所有ajax的请求都会阻止重复提交,也可以通过传avoidDuplicateRequesting来阻止单个的重复提交 InRequestingCache = {};//cache request for duplicate check ajax.setAvoidDuplicateRequesting = function(type){ avoidDuplicateRequesting = type; } ajax.extendParams = function(options,params){ return Object.assign({},options,{ beforeSend:function(){ console.log('beforeSend'); if( ({}).hasOwnProperty.call(options,'beforeSend') ) ajax.addBeforeSendInterceptors(options['beforeSend']) return beforeSendInterceptors.every((fn)=>fn.call(null,options)) },complete:function() { if( ({}).hasOwnProperty.call(options,'complete') ) ajax.addCompleteInterceptors( options['beforeSend'] ) completeInterceptors.forEach((fn)=>fn.call(null,options)); console.log('complete') ajax.clearInRequestingCache(); },},params); } ajax.addBeforeSendInterceptors = function(fn){ beforeSendInterceptors.unshift(fn); return ()=>{ beforeSendInterceptors.filter((item)=>item!=fn);//返回一个反注册函数 unlistener } } ajax.addCompleteInterceptors = function(fn){ completeInterceptors.push(fn); return ()=>{ completeInterceptors.filter((item)=>item!=fn); } } ajax.clearInterceptors = function(){ beforeSendInterceptors = []; completeInterceptors = []; } ajax.clearInRequestingCache = function(key){ key && (delete InRequestingCache[key]) || (InRequestingCache = {}); console.log('clear:'+key); } ajax.addRequestingInProgress = function(key){ InRequestingCache[key] = true; } ajax.isRequestingInProgress = function(key){ return ({}).hasOwnProperty.call(InRequestingCache,key) ? true : false; } return ajax; })() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |