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
862 views
in Technique[技术] by (71.8m points)

javascript - Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload

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

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

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>

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 shows a similar behavior. Intead of just overwriting the request header it modifies it to Cache-Control: no-cache, max-age=0 on F5.

Can I suppress this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


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

...