ajax拦截器 重复提交

前端之家收集整理的这篇文章主要介绍了ajax拦截器 重复提交前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
/**
 * 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;
    })()
原文链接:https://www.f2er.com/ajax/161296.html

猜你在找的Ajax相关文章