强制缓存控制:在 F5 重新加载时通过 XMLHttpRequest 在 Chrome 中无缓存 [英] Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload

查看:26
本文介绍了强制缓存控制:在 F5 重新加载时通过 XMLHttpRequest 在 Chrome 中无缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保我通过 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

但如果用户按 F5,我的 Chrome 版本 33 会使用 Cache-Control: max-age=0 覆盖此标头.

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

示例.将 test.html 与内容放在您的网络服务器上

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>

在网络选项卡上的 chrome 调试器中,我看到了 test.html AJAX 调用.状态代码 200.现在按 F5 重新加载页面.有 max-age: 0 和状态代码 304 Not Modified.

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.

Firefox 显示了类似的行为.Intead 只是覆盖请求标头,它将其修改为 Cache-Control: no-cache, max-age=0 on 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.

我可以抑制这个吗?

推荐答案

另一种方法是在 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.

这篇关于强制缓存控制:在 F5 重新加载时通过 XMLHttpRequest 在 Chrome 中无缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆