How to set cache: false in jQuery.get call

前端 未结 7 480
天涯浪人
天涯浪人 2020-11-28 04:07

jQuery.get() is a shorthand for jQuery.ajax() with a get call. But when I set cache:false in the data of the .get() call

相关标签:
7条回答
  • 2020-11-28 04:35

    To me, the correct way of doing it would be the ones listed. Either ajax or ajaxSetup. If you really want to use get and not use ajaxSetup then you could create your own parameter and give it the value of the the current date/time.

    I would however question your motives in not using one of the other methods.

    0 讨论(0)
  • 2020-11-28 04:35

    I'm very late in the game, but this might help others. I hit this same problem with $.get and I didn't want to blindly turn off caching and I didn't like the timestamp patch. So after a little research I found that you can simply use $.post instead of $.get which does NOT use caching. Simple as that. :)

    0 讨论(0)
  • 2020-11-28 04:38

    Per the JQuery documentation, .get() only takes the url, data (content), dataType, and success callback as its parameters. What you're really looking to do here is modify the jqXHR object before it gets sent. With .ajax(), this is done with the beforeSend() method. But since .get() is a shortcut, it doesn't allow it.

    It should be relatively easy to switch your .ajax() calls to .get() calls though. After all, .get() is just a subset of .ajax(), so you can probably use all the default values for .ajax() (except, of course, for beforeSend()).

    Edit:

    ::Looks at Jivings' answer::

    Oh yeah, forgot about the cache parameter! While beforeSend() is useful for adding other headers, the built-in cache parameter is far simpler here.

    0 讨论(0)
  • 2020-11-28 04:39

    I think you have to use the AJAX method instead which allows you to turn caching off:

    $.ajax({
      url: "test.html",
      data: 'foo',
      success: function(){
        alert('bar');
      },
      cache: false
    });
    
    0 讨论(0)
  • 2020-11-28 04:43

    Set cache: false in jQuery.get call using Below Method

    use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond.

    Or

    The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)

    $.ajaxSetup({ cache: false });
    
    0 讨论(0)
  • 2020-11-28 04:53

    Note that callback syntax is deprecated:

    Deprecation Notice

    The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

    Here a modernized solution using the promise interface

    $.ajax({url: "...", cache: false}).done(function( data ) {
        // data contains result
    }).fail(function(err){
        // error
    });
    
    0 讨论(0)
提交回复
热议问题