Pass the same options to a jQuery function over an

2019-08-17 04:46发布

问题:

I use this jQuery Ajax-Request, which I configured for my needs:

jQuery.ajax({
    url: "apiBridge.php?url=" +  encodeURIComponent(url),
    headers: {
        "Some Weird Header": "123"
    },
    success: function(data){

    },
    complete: function(){
        doAlotOfStuff();
        andMore();
    }
});

The real code is fairly lengthy and I consider it stupid to copy/paste the whole thing every time I need to make an Ajax-request in my style.

What I want to do, is to define this function once, so I am able to re-use it. All I need to change for each instace of the function is the url and success callback.

What is the right way to do this?

回答1:

Define a set of standard options:

var ajaxOpts = {
    headers:{},
    url:"someUrl",
    complete:function(){//whatever;},
    otheroptions:"asneeded"
};

When you make each ajax call, extend the local options object with the standard options:

$.ajax($.extend({url:"custom", success:doAThing}, ajaxOpts));

...or as @gdoron says, use ajaxSetup. I prefer $.extend because that way I'm not clobbering other $.ajax calls on the page I might not control.



回答2:

You can use the ajaxSetup function.

jQuery.ajaxSetup( options )

Description: Set default values for future Ajax requests.