如何在 jQuery 中为 getJSON 设置缓存 false?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13391563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:35:02  来源:igfitidea点击:

How to set cache false for getJSON in jQuery?

jqueryjquery-uigetjsonbrowser-cache

提问by Abhinav

I am using getJSONto 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 getJSONcall.

我正在使用getJSON从服务器端获取结果但面临浏览器缓存问题。我希望缓存为假。我在getJSON打电话之前尝试使用它。

 $.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 .ajaxbut I really don't want to use that.

我还确定了一些其他解决方案,例如使用,.ajax但我真的不想使用它。

回答by bonesnatch

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

您的代码只需要一个触发器即可启用它。

This will allow you to disable cache in all future ajax

这将允许您在以后的所有 ajax 中禁用缓存

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

Hope it helps :)

希望能帮助到你 :)

回答by semente

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:

或者,而不是$.getJSON,仅针对此类请求禁用缓存:

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

回答by TriumphST

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.

semente 和 bonenatch 的答案是正确的,但是如果您想使用 $.getJSON 和其他地方,请利用它的缓存(您不想将所有调用的缓存设置为 false),但您只想破坏缓存单个调用,您可以将时间戳注入 $.getJSON() 的数据属性。通过向请求的查询字符串添加唯一值,请求将始终是唯一的,不会被浏览器缓存——您将始终获得最新数据。

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.

其中末尾的数字是调用代码时的时间戳,因此将始终是唯一的。