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 iss
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});
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.
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.
For those of you using the cache
option of $.ajaxSetup()
on mobile Safari, it appears that you may have to use a timestamp for POSTs, since mobile Safari caches that too. According to the documentation on $.ajax()
(which you are directed to from $.ajaxSetup()
):
Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.
So setting that option alone won't help you in the case I mentioned above.
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.
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 result, working for Chrome at least, would be:
$.ajax({
url: url,
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
}
});