Difference between $.ajax(); and $.ajaxSetup();
JqueryAjaxJquery Problem Overview
What is the difference between $.ajax();
and $.ajaxSetup();
in jQuery as in:
$.ajax({
cache:false
});
and
$.ajaxSetup({
cache:true
});
Also, which one is best option?
Jquery Solutions
Solution 1 - Jquery
The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
you should use $.ajax, which will allow you to turn caching off for that instance:
$.ajax({url: "myurl", success: myCallback, cache: false});
Solution 2 - Jquery
ajaxSetup
sets default values to be valid for all ajax requests. After this you don't have to do the same setting in $.ajax
All settings in $.ajax
will be valid only for that ajax call.
Solution 3 - Jquery
The first one disables cache on a per request basis, the second one sets it up to be disabled globally by default for all AJAX functions.
Solution 4 - Jquery
To avoid caching, one option is to give different URL for the same resource or data. To generate different URL, you can add a random query string to the end of the URL. This technique works for JQuery, Angular or other type ajax requests.
myURL = myURL +"?random="+new Date().getTime();
JQuery uses the similar technique via $.ajax({cache:false});
and $.ajaxSetup({cache:false});
$.ajax({cache:false})
applies the technique on which it is included, $.ajaxSetup({cache:false});
applies the technique for all AJAX functions.
Solution 5 - Jquery
> Also, which one is best option?
According to jQuery api documentation, using $.ajaxSetup()
is not recommended:
> 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.