在jquery中更改缓存时间

Maj*_*Afy 7 ajax jquery json caching

如果我们通过truecache$.ajax()jQuery的将缓存加载的数据,我想知道有没有办法改变的缓存时间$.ajax()?例如,如果ajax在10分钟内请求jquery加载以前的数据,但如果在10分钟后请求加载新数据.

更新:

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

jma*_*777 5

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

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

var cacheBuster = new Date().getTime();
setInterval(function() {
    cacheBuster = new Date().getTime();
}, 1000 * 60 * 10)
Run Code Online (Sandbox Code Playgroud)

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


编辑:为了使它成为一个更完整的解决方案,下面是一个示例,该示例说明如何cacheBuster在所有jQuery Ajax请求上透明地对实际Ajax调用使用:

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