[英]Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload
我想确保我通过 AJAX 调用请求的数据是最新的并且没有被缓存。 为此,我发送了 header Cache-Control: no-cache
但是如果用户按 F5,我的 Chrome 版本 33 会使用Cache-Control: max-age=0
。
例子。 在您的网络服务器上放置一个test.html
内容
<script>
var xhr = new XMLHttpRequest;
xhr.open('GET', 'test.html');
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.send();
</script>
在 .network 选项卡上的 chrome 调试器中,我看到了 test.html AJAX 调用。 状态代码 200。现在按 F5 重新加载页面。 有 max-age: 0 和状态码 304 Not Modified。
Firefox 显示了类似的行为。 Intead 只是覆盖请求 header,它在 F5 上将其修改为 Cache-Control: no-cache, max-age=0。
我可以压制这个吗?
另一种方法是在 url 后附加一个唯一的数字。
<script>
var xhr = new XMLHttpRequest;
xhr.open('GET', 'test.html?_=' + new Date().getTime());
//xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.send();
</script>
时间戳不是很独特,但它对于您的用例来说应该足够独特。
由于多种原因,现在使用查询字符串进行缓存控制并不是您的最佳选择,并且(仅)在此答案中提到了一些。 他甚至解释了版本控制的新标准方法。 但是,如果您只想设置请求标头,正确的做法是:
// via Cache-Control header:
xhr.setRequestHeader("Cache-Control", "no-cache, no-store, max-age=0");
// fallbacks for IE and older browsers:
xhr.setRequestHeader("Expires", "Tue, 01 Jan 1980 1:00:00 GMT");
xhr.setRequestHeader("Pragma", "no-cache");
希望这对未来的任何人都有帮助。
我尝试(但失败)对 URL 进行某种随机化,但它不起作用,因为我正在访问的文件 (.json) 也被缓存。
我的解决方案是在对 json 文件名的调用中添加时间戳(与上述方法类似,稍作修改)。 这对我来说非常有效(下面的代码片段)。
doSomething('files/data.json?nocache=' + (new Date()).getTime(), function(text){...
我对这一切都很陌生,所以我确定这不是标准/正确的解决方案是有原因的,但它对我有用。
删除元素并使用 jQuery(我认为也是 JS)添加新元素在 Chrome 中对我有用。
// Wordpress Context, selectedImage is an object from the Media Selector Dialog
const imageID = selectedImage.id
const imageURL = selectedImage.url
// This is a div with the img as an only child
const logoImageContainer = $('#q1nv0-preview-image-container')
let clone = $(logoImageContainer).find('img').clone()
// In the cloned img object I change the src to the new image
clone.removeAttr("src").attr('src', imageURL)
// Also I have to remove this in wordpress context:
clone.removeAttr("srcset")
// the div is cleared of the old image
$('#q1nv0-preview-image-container').empty()
// the new image is added to the div
$(logoImageContainer).prepend(clone)
http.setRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.