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()
?
another way is to provide no cache headers from serverside in the code that generates the response to ajax call:
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.
Of course this doesn't help if you have no control over the server.
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).
I 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).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()
):So setting that option alone won't help you in the case I mentioned above.
If you are using .net ASP MVC, disable the caching on the controller action by adding the following attribute on the end point function: [OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)