如何防止浏览器缓存json文件 [英] How to prevent the browser from caching a json file

查看:812
本文介绍了如何防止浏览器缓存json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在做这个小项目,并且在捕捉时遇到一些麻烦。有一件事情不起作用,浏览器一直在缓存包含保存数据的json文件,而当我在其他地方更新json时,浏览器会返回到已缓存的旧版json文件并将其读取。不幸的是我不想要那样。我不希望浏览器缓存文件,以便每次加载页面时,它都会向服务器请求json文件,并根据该文件而不是缓存的任何文件进行操作。不过,我希望能够缓存页面上的所有其他内容,但如果必须牺牲这个功能,那么这是我愿意做出的牺牲。我设想在JavaScript中会有一个调用放弃当前的json文件并再次询问服务器或类似的东西。

 < script src =mySaveFiles.jsoncache =no> 

或类似的东西来帮助我实现我正在谈论的内容... help?

解决方案

最简单的方法是在源字符串后添加一些随机参数, b
$ b

 < script src =mySaveFiles.json?nocache = 123>< / script> 

一个解决方案是使用JavaScript生成脚本元素并将当前时间附加到这样:

  var el = document.createElement(script); 
el.src ='mySaveFiles.json?nocache ='+(new Date())。getTime();
document.head.appendChild(el);

这样,浏览器永远不会缓存JSON文件,因为它看起来像是一个不同的文件由于参数)在每次调用。


So I'm making this little project and I'm having some troubles with catching. One thing that's not working is the browser keeps caching the json file that contains save data and when I update the json somewhere else, the browser goes back to the old version of the json file that it has cached and reads off that. Unfortunately I dont want that. I dont want the browser to cache the file at all so that every time it loads up the page, it'll ask the server for the json file and act according to that file instead of whatever file that it has cached. I would however like to be able to cache all the other stuff that's on the page but if that has to be sacrificed for this to work then it's a sacrifice I'm willing to make. I'm envisioning that in JavaScript that there would be a call that says discard the current json file and go ask the server again for it or something like

<script src="mySaveFiles.json" cache="no"> 

or something of the sort to help me achieve what I'm talking about... help?

解决方案

The easiest way is to append the source string with some random parameter, which gets ignored on the server side

<script src="mySaveFiles.json?nocache=123" ></script>

One solution would be to generate the script element using JavaScript and append the current time like this:

var el = document.createElement( script );
el.src = 'mySaveFiles.json?nocache=' + (new Date()).getTime();
document.head.appendChild( el );

That way, the browser will never cache the JSON-file as it appears to be a different file (due to the parameter) in every call.

这篇关于如何防止浏览器缓存json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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