It looks like that if I load dynamic content using $.get(), the result is cached in browser. Adding some random string in QueryString seem 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() ?
Source: Tips4all
I use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond.
ReplyDeleteThe following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)
ReplyDelete$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
Personally I feel that the query string method is more reliable than trying to set headers on the server - there's no guarantee that a proxy or browser won't just cache it anyway (some browsers are worse than others - naming no names).
ReplyDeleteI usually use Math.random() but I don't see anything wrong with using the date (you shouldn't be doing AJAX requests fast enough to get the same value twice).
A small addition to the excellent answers given: If you're running with a non-ajax backup solution for users without javascript, you will have to get those server-side headers correct anyway. This is not impossible, although I understand those that give it up ;)
ReplyDeleteI'm sure there's another question on SO that will give you the full set of headers that are appropriate. I am not entirely conviced miceus reply covers all the bases 100%.
What about using a POST request instead of a GET...?
ReplyDelete(Which you should anyway...)
Of course "cache-breaking" techniques will get the job done, but this would not happen in the first place if the server indicated to the client that the response should not be cached. In some cases it is beneficial to cache responses, some times not. Let the server decide the correct lifetime of the data. You may want to change it later. Much easier to do from the server than from many different places in your UI code.
ReplyDeleteOf course this doesn't help if you have no control over the server.
You can use the short notation $.now() instead of doing a (new Date().getTime()) each and everytime.
ReplyDelete