gpt4 book ai didi

ajax - 更改jquery中的缓存时间

转载 作者:行者123 更新时间:2023-12-03 22:39:43 25 4
gpt4 key购买 nike

如果我们在$.ajax()中为cache传递true,jquery将缓存加载的数据,我想知道有什么方法可以更改 $.ajax() 的缓存时间?例如,如果 ajax 在 10 分钟内请求,jquery 将加载以前的数据,但如果在 10 分钟后请求,则加载新数据。

更新:

我们需要缓存 JSON 数据,所以我应该在 JSON 数据类型中使用 Ajax

最佳答案

当您设置 cache 时,jQuery 实际上不会为您缓存请求。至false ,它只是设置一些 header 并传递一个“缓存破坏者”查询字符串变量(例如 ?_=487262189472 )以防止浏览器或任何代理返回缓存的响应。

如果您想要 10 分钟的缓存,您可以相当轻松地实现自己的缓存。例如,

var cacheBuster = new Date().getTime();
setInterval(function() {
cacheBuster = new Date().getTime();
}, 1000 * 60 * 10)

然后只需将其添加到您的请求的查询字符串变量中(例如 ?_noCache=<cacheBuster> )。

<小时/>

编辑:为了使其成为更完整的解决方案,以下是如何使用 cacheBuster 的示例所有 jQuery Ajax 请求对实际 Ajax 调用都是透明的:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var startChar = options.url.indexOf('?') === -1 ? '?' : '&';
options.url += startChar + '_noCache=' + cacheBuster;
});

关于ajax - 更改jquery中的缓存时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10585578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com