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

前端 未结 3 1125
礼貌的吻别
礼貌的吻别 2020-12-08 12:09

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

相关标签:
3条回答
  • 2020-12-08 12:46
    http.setRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    
    0 讨论(0)
  • 2020-12-08 12:48

    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.

    0 讨论(0)
  • 2020-12-08 12:50

    Using a query string for cache control isn't your best option nowadays for multiple reasons, and (only) a few are mentioned in this answer. He even explains the new standard method of version control. Though if you just want to be able to set your request headers, the right way to do it is:

    xhr.setRequestHeader('cache-control', 'no-cache, must-revalidate, post-check=0, pre-check=0');
    xhr.setRequestHeader('cache-control', 'max-age=0');
    xhr.setRequestHeader('expires', '0');
    xhr.setRequestHeader('expires', 'Tue, 01 Jan 1980 1:00:00 GMT');
    xhr.setRequestHeader('pragma', 'no-cache');
    

    Hope this helps anyone in the future.

    0 讨论(0)
提交回复
热议问题