Reputation: 69
var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
var xhr = _orgAjax();
DoSomeLogging();
return xhr;
};
I've inherited the code above. Can someone confirm my understanding that this will override any $.ajax(...)
call anywhere else on the page and execute DoSomeLogging()
each time?
I'm hunting a different bug but stumbled upon this and wanted to be sure I understand what this piece of legacy code does?
I'm not convinced this is good practice/use of the xhr
function anyway but interested to hear your opinions. We're using Jquery 1.7.1.
Lastly, out of curiosity, what if _orgAjax()
failed to return if an (async: false
) call, would the logging method even get reached?
Thanks.
Upvotes: 2
Views: 16443
Reputation: 22339
Can someone confirm my understanding that this will override any $.ajax(...) call anywhere else on the page and execute DoSomeLogging() each time?
Yes. This will define the global default behaviour unless overwritten in a local ajax implementation.
The more documented way of defining global settings is the use of ajaxSetup().
However, you are able to set default global behaviour using ajaxSettings
as well, though this particular way is not documented anywhere directly in the jQuery documentation.
See DEMO - With Success
Lastly, out of curiosity, what if _orgAjax() failed to return if an (async: false) call, would the logging method even get reached?
The settings are configuring the beforeSend
so the logging method will always be called regardless of the async setting as pointed out correctly by Esailija.
See DEMO - with async: true
, logging is called before return
See DEMO - with async: false
, logging is also called before return
However please note though, according to the ajax documentation:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is
deprecated; you must use the complete/success/error callbacks.
I know you are using 1.7.1 but if something becomes deprecated there usually is a good reason and I don't see any harm in preparing for that.
To configure ajax with logging on complete
by default:
See DEMO - Configuring default logging for complete
for document.
I know that would make your logging being executed after and not before the send but that seems to be the way 1.8 prefers it I think.
Upvotes: 4
Reputation: 185943
Hm, you could:
$.ajaxSetup({
beforeSend: function () {
doSomeLogging();
}
});
That's certainly simpler than having to redefine $.ajaxSettings.xhr
.
Upvotes: 0