vsahu vsahu - 1 year ago 77
Ajax Question

Does calling jQuery's ajaxSetup with no parameters have any side effects?

I've read the answers here and here that describe how to read the value of jQuery ajax settings. My question, however, is this: if I have previously invoked the ajaxSetup function with settings, like

$.ajaxSetup({cache: true})
, and then I invoke
(with no arguments), are there any side effects to this invocation? Or more bluntly, does calling
with no arguments do anything
other than return a plain object that contains the settings for ajax?

The answers I've referenced above both call ajaxSetup in this way in order to read the value of a setting, and I have been unable to find any official answer on the jQuery docs that indicate what calling ajaxSetup with no parameters does, probably because its use is so heavily discouraged. In my browser, I ran a simple test by loading jQuery, running
$.ajaxSetup({async: false});
followed by
and found that the value of async was still unchanged (the default value is true, and so if calling
reset the settings to default values, then the value of async should have been changed), but this probably isn't strong enough evidence to conclude that side effects do not occur when the function is invoked in this way.

Answer Source

Does calling $.ajaxSetup() with no arguments do anything other than return a plain object that contains the settings for ajax?



// set a new custom url
  url: 'CHANGED'

// call it again with no params

// the url is still the custom url
console.log('url: ' + $.ajaxSetup().url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


If we look at the code for ajaxSetup, we see that, when called with a single parameter, it returns the call:

ajaxExtend( jQuery.ajaxSettings, target );

where target is the single argument you passed into ajaxSetup().

Now, inside ajaxExtend, we can see that it tries to iterate over that same argument with a for in loop.

Relevant code:

function ajaxExtend( target, src ) {

    for (var key in src) {
      // here is where target, which in this case is jQuery.ajaxSettings, gets overriden

    return target;

Since you don't pass anything, basically you are doing

function ajaxExtend( target, src ) {

    for (var key in undefined) {
      // this is never reached

    return target;

which never enters the for in loop and returns the current value of jQuery.ajaxSettings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download