Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a scope be set for jquery.ajaxSetup()?

I'm working on something with a ton of ajax calls, most of which have the same parameters. I'm considering using jquery.ajaxSetup() to cut down on the code.

However, jQuery doesn't like it's API for this. It says:

Note: The settings specified here will affect all calls to $.ajax or AJAX-based 
derivatives such as $.get(). This can cause undesirable behavior since other callers (for 
example, plugins) may be expecting the normal default settings. For that reason we
strongly recommend against using this API. Instead, set the options explicitly in the call
or define a simple plugin to do so.

Is there a way to implement this so it doesn't touch every js file, including plugins? I'm not using an external jQuery plugins that work with ajax right now, but I want to future-proof this for future developers if possible. Is it possible jQuery will drop this from it's API?

like image 668
streetlight Avatar asked Jan 22 '26 06:01

streetlight


1 Answers

How about wrapper the ajax() call with code like this:

var sendAjax = function (options) {
    var type = 'GET';
    var dataType = 'json';
    var success = options.onsuccess || function () {};
    var error = options.onerror || function () {};
    var url = options.url;
    var data = options.data;
    $.ajax({
        type: type,
        url: url,
        data: data,
        dataType: dataType ,
        success: success ,
        error: error
    });
};

Then replace your ajax call to sendAjax();

like image 57
Franky Yang Avatar answered Jan 24 '26 20:01

Franky Yang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!