Difference between $.ajax(); and $.ajaxSetup();

后端 未结 5 1445
温柔的废话
温柔的废话 2020-12-01 04:18

What is the difference between $.ajax(); and $.ajaxSetup(); in jQuery as in:

$.ajax({
    cache:false
});

and

相关标签:
5条回答
  • 2020-12-01 04:32

    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.

    0 讨论(0)
  • 2020-12-01 04:33

    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});
    
    0 讨论(0)
  • 2020-12-01 04:41

    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.

    0 讨论(0)
  • 2020-12-01 04:54

    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.

    0 讨论(0)
  • 2020-12-01 04:59

    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.

    0 讨论(0)
提交回复
热议问题