力的Cache-Control:通过对F5重装XMLHtt prequest无缓存在Chrome重装、缓存、Control、Cache

2023-09-10 18:07:11 作者:埋葬♂回忆

我要保证我的数据通过Ajax调用请求是新鲜的,而不是缓存。为此我送的标题的Cache-Control:no-cache的

I want to ensure that data I request via an AJAX call is fresh and not cached. Therefor I send the header Cache-Control: no-cache

但我的浏览器版本33的覆盖与的Cache-Control这个头:最大年龄= 0 如果用户presses F5

But my Chrome Version 33 overrides this header with Cache-Control: max-age=0 if the user presses F5.

为例。将一个的test.html 在您的Web服务器与内容

Example. Put a test.html on your webserver with the contents

<script>
    var xhr = new XMLHttpRequest;
    xhr.open('GET', 'test.html');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send();
</script>

在网络选项卡上的镀铬调试我看到的test.html AJAX调用。状态code 200现在preSS F5刷新页面。还有就是最大年龄:0,和状态code 304未修改。

In the chrome debugger on the network tab I see the test.html AJAX call. Status code 200. Now press F5 to reload the page. There is the max-age: 0, and status code 304 Not Modified.

火狐显示了类似的行为。这一翻译只是覆盖请求头它修改到高速缓存控制:无缓存,最大年龄= 0 F5

Firefox shows a similar behavior. Intead of just overwriting the request header it modifies it to Cache-Control: no-cache, max-age=0 on F5.

我可以晚饭preSS呢?

Can I suppress this?

推荐答案

的Cache-Control是一个响应头,而不是一个请求头。您需要使用您的Web服务器来设置它。

Cache-Control is a response header, not a request header. You need to set it using your webserver.

另一种方法是将附加一个唯一编号的URL。

An alternative would be to append a unique number to the url.

<script>
    var xhr = new XMLHttpRequest;
    xhr.open('GET', 'test.html?_=' + new Date().getTime());
    //xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send();
</script>

时间戳是不是很独特,但它应该是为你的用例够独特。

timestamp isn't quite unique, but it should be unique enough for your usecase.