Prevent browser caching of jQuery AJAX call result

2018-12-31 09:07发布

It looks like if I load dynamic content using $.get(), the result is cached in browser.

Adding some random string in QueryString seems to solve this issue (I use new Date().toString()), but this feels like a hack.

Is there any other way to achieve this? Or, if unique string is the only way to achieve this, any suggestions other than new Date()?

20条回答
步步皆殇っ
2楼-- · 2018-12-31 09:25

What about using a POST request instead of a GET...? (Which you should anyway...)

查看更多
只若初见
3楼-- · 2018-12-31 09:25

As @Athasach said, according to the jQuery docs, $.ajaxSetup({cache:false}) will not work for other than GET and HEAD requests.

You are better off sending back a Cache-Control: no-cache header from your server anyway. It provides a cleaner separation of concerns.

Of course, this would not work for service urls that you do not belong to your project. In that case, you might consider proxying the third party service from server code rather than calling it from client code.

查看更多
孤独总比滥情好
4楼-- · 2018-12-31 09:27

I use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond:

$.get('/getdata?_=' + new Date().getTime(), function(data) {
    console.log(data); 
});

Edit: This answer is several years old. It still works (hence I haven't deleted it), but there are better/cleaner ways of achieving this now. My preference is for this method, but this answer is also useful if you want to disable caching for every request during the lifetime of a page.

查看更多
春风洒进眼中
5楼-- · 2018-12-31 09:27

JQuery's $.get() will cache the results. Instead of

$.get("myurl", myCallback)

you should use $.ajax, which will allow you to turn caching off:

$.ajax({url: "myurl", success: myCallback, cache: false});
查看更多
深知你不懂我心
6楼-- · 2018-12-31 09:29

Maybe you should look at $.ajax() instead (if you are using jQuery, which it looks like). Take a look at: http://docs.jquery.com/Ajax/jQuery.ajax#options and the option "cache".

Another approach would be to look at how you cache things on the server side.

查看更多
有味是清欢
7楼-- · 2018-12-31 09:30

All the answers here leave a footprint on the requested URL which will show up in the access logs of server.

I needed a header based solution with no side effect and I found it can be achieved by setting up the headers mentioned in How to control web page caching, across all browsers?.

The results, working for Chrome at least, would be

$.ajax({
   url: url, 
   headers: {
     'Cache-Control': 'no-cache, no-store, must-revalidate', 
     'Pragma': 'no-cache', 
     'Expires': '0'
   }
});

查看更多
登录 后发表回答