Extending jQuery ajax success globally

后端 未结 5 1913
庸人自扰
庸人自扰 2021-01-03 03:19

I\'m trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific st

5条回答
  •  孤城傲影
    2021-01-03 03:55

    You can build your own AJAX handler instead of using the default ajax:

    var ns = {};
    ns.ajax = function(options,callback){ 
        var defaults = {              //set the defaults
            success: function(data){  //hijack the success handler
                if(check(data)){       //checks
                    callback(data);   //if pass, call the callback
                }
            }
        };
        $.extend(options,defaults);  //merge passed options to defaults
        return $.ajax(options);             //send request
    }
    

    so your call, instead of $.ajax, you now use;

    ns.ajax({options},function(data){
        //do whatever you want with the success data
    });
    

提交回复
热议问题