简体   繁体   English

强制AJAX请求重新验证服务器的缓存,而无需完全重新加载

[英]Forcing AJAX request to revalidate cache with server, without reloading completely

I have a web application that lets the browser cache AJAX requests result for a long time. 我有一个Web应用程序,可让浏览器长时间缓存AJAX请求结果。 I have found out how to make a request that bypasses the cache entirely, when probable modifications are detected. 我发现在检测到可能的修改时如何发出完全绕过缓存的请求。 But I would want to let the user trigger a data refresh. 但是我想让用户触发数据刷新。

In this scenario, I'd like the browser to check with the server if the cache is stalled but use it if it is not (that is, if the server responds with a 304 code). 在这种情况下,我希望浏览器与服务器一起检查缓存是否已停止, 如果缓存没有停止,则使用缓存(即服务器是否以304代码响应)。 The goal is to spare the loading time because the data is huge. 目标是节省加载时间,因为数据量很大。

The server includes the following headers in all responses: 服务器在所有响应中都包含以下标头:

Cache-Control: private, max-age=604800
Last-Modified: ... # actual last modification date

I managed to burst the cached object entirely in Chrome (not tested other browsers yet) by using the following HTTP headers in the request: 通过在请求中使用以下HTTP标头,我设法完全在Chrome浏览器中缓存了缓存的对象(尚未经过其他浏览器的测试):

Cache-Control: max-age=0
If-Last-Modified: Tue, 01 Jan 1970 01:00:00 +0100

The If-Last-Modified line is the one that really has an effect. If-Last-Modified行是真正起作用的行。 Chrome seems to ignore the Cache-Control header in the request. Chrome似乎忽略了请求中的Cache-Control标头。

I have also found that using Cache-Control: must-revalidate in the server response forces the browser to validate its cache with the server for each request. 我还发现,在服务器响应中使用Cache-Control: must-revalidate强制浏览器针对每个请求向服务器验证其缓存。

But is there any way to revalidate for just one precise request, decided on the client-side ? 但是,是否有任何方法可以仅针对一个精确的请求重新验证( 由客户端决定)

Note that I'm not specially attached to doing this with HTTP headers, so any other method that I would not be aware of is welcome! 请注意,我并不是特别喜欢使用HTTP标头来执行此操作,因此欢迎使用我不知道的任何其他方法!

you can add a url parameter which value base on time to clean cache for just one precise request. 您可以添加一个基于时间的url参数,以仅针对一个精确请求清除缓存。

$.ajax({
    url:"/questions?nocache="+Date.now(),
    "success":function(data){
         console.log(data);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM