[英]How can I avoid cached data when downloading via XMLHttpRequest()
I am writing an extension for the Chrome browser (and later hope to port to Firefox). 我正在为Chrome浏览器编写扩展程序(后来希望移植到Firefox)。 The extension downloads a configuration file from my server - an xml file via XMLHttpRequest. 扩展程序从我的服务器下载配置文件 - 通过XMLHttpRequest的xml文件。 What I am find is that it downloads the file once and every subsequent call simply seems to use the cached original version of the file. 我发现它是一次下载文件,每次后续调用似乎只是使用文件的缓存原始版本。 It doesn't matter whether or not I change the file on the server. 无论我是否更改服务器上的文件都无关紧要。
I read that you could try 我读过你可以试试
xmlhttp.setRequestHeader( 'Pragma', 'Cache-Control: no-cache'); xmlhttp.setRequestHeader('Pragma','Cache-Control:no-cache');
and so I've done this but it doesn't seem to make any difference. 所以我已经做到了这一点,但它似乎没有任何区别。 The only way I can get the new file seems to be to delete the browser cache - which obviously is not a solution for my growing users. 我可以获得新文件的唯一方法似乎是删除浏览器缓存 - 这显然不是我不断增长的用户的解决方案。
This seems like a problem that I wouldn't be the first person to experience - so given thatcacheing rules seem to uphold this as a policy that can't be easily avoided, my question is, what's the better design? 这似乎是一个问题,我不会是第一个体验的人 - 所以考虑到缓存规则似乎坚持这是一个不容易避免的政策,我的问题是,什么是更好的设计? is there a best practice I don't know about? 有没有我不了解的最佳做法? Should I be pushing rather than pulling somehow? 我应该推动而不是以某种方式拉动?
An easy way is to add a useless parameter containing the time to the request. 一种简单的方法是向请求添加包含时间的无用参数。 Since time tends to go forwards and never backwards, you can be reasonably sure that your query is unique and therefore won't be cached. 由于时间趋向于前进而且从不向后,您可以合理地确定您的查询是唯一的,因此不会被缓存。
For instance (assuming the URL is in a string url
): 例如(假设URL在字符串url
):
url += '?_time=' + (new Date()).getTime();
or, if your URL already has query parameters, 或者,如果您的URL已经有查询参数,
url += '&_time=' + (new Date()).getTime();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.