How to set cache false for getJSON in jQuery?

泄露秘密 提交于 2019-11-26 04:46:01

问题


I am using getJSON to fetch the results from server side but facing browser cache problems. I want the cache to be false. I tried using this just before my getJSON call.

 $.ajaxSetup({
                cache: false
            })

But I am not getting the expected results. It still shows the old results.

I also identified some other solutions such as using .ajax but I really don\'t want to use that.


回答1:


Your code just needs a trigger for it to be enabled.

This will allow you to disable cache in all future ajax

$(document).ready(function() {
  $.ajaxSetup({ cache: false });
});

Hope it helps :)




回答2:


You can use either this, that will disable cache globally:

$(document).ready(function() {
  $.ajaxSetup({ cache: false });
});

or that, instead of $.getJSON, to disable the cache just for such request:

$.ajax({
    cache: false,
    url: "/path/to.json",
    dataType: "json",
    success: function(data) {
        ...
    }
});



回答3:


semente's and bonesnatch's answers are correct, but if you want to use $.getJSON and elsewhere take advantage of it's caching (you don't want to set the cache to false for all calls), but you want to bust the cache just for a single call, you can inject a timestamp into data property of $.getJSON(). By adding a unique value to the query string of the request, the request will always be unique and not be cached by the browser - you will always get the latest data.

Long version:

var ts = new Date().getTime();
var data = {_: ts};
var url = '/some/path.json';

$.getJSON(url, data);

All in one version:

$.getJSON('/some/path', {_: new Date().getTime()});

Both result in the following request:

/some/path.json?_=1439315011130 

where the number at the end is the timestamp for the moment that the code is called and will therefore always be unique.



来源:https://stackoverflow.com/questions/13391563/how-to-set-cache-false-for-getjson-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!