Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

javascript - How to prevent the browser from caching a json file

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...