3

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?

streetlight
  • 5,968
  • 13
  • 62
  • 101
  • 1
    Could you code your own wrapper function for `$.ajax()` to set the options? Then you wouldn't need to repeat the common ajax options in multiple places in your code, you'd just call the wrapper instead of `$.ajax()`. You could code the wrapper to take options as an argument so that it could override its defaults selectively. – nnnnnn May 20 '13 at 12:24

1 Answers1

4

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();

Franky Yang
  • 221
  • 2
  • 6
  • Totally functional approach -- I may choose to send an object as options instead by I like your general approach, which doesn't use ajaxSetup at all. Thanks! – streetlight May 20 '13 at 12:50
  • Note that this could be extended by defining the defaults as an object rather than as individual variables, and then looping through the `options` argument's properties and copying them into the defaults object. (Or use [`$.extend()`](http://api.jquery.com/jquery.extend/) to merge them.) That way you can pass any number of options to `sendAjax()`. – nnnnnn May 20 '13 at 12:50