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()
?
Now, it's easy to do it by enabling/disabling cache option in your ajax request, just like this
Basically just add
cache:false;
in the ajax where you think the content will change as the progress go on. And the place where the content wont change there u can omit this. In this way u will get the new response every timeappend Math.random() to the request url
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 ;)
I'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%.
The real question is why you need this to not be cached. If it should not be cached because it changes all the time, the server should specify to not cache the resource. If it just changes sometimes (because one of the resources it depends on can change), and if the client code has a way of knowing about it, it can append a dummy parameter to the url that is computed from some hash or last modified date of those resources (that's what we do in Microsoft Ajax script resources so they can be cached forever but new versions can still be served as they appear). If the client can't know of changes, the correct way should be for the server to handle HEAD requests properly and tell the client whether to use the cached version or not. Seems to me like appending a random parameter or telling from the client to never cache is wrong because cacheability is a property of the server resource, and so should be decided server-side. Another question to ask oneself is should this resource really be served through GET or should it go through POST? That is a question of semantics, but it also has security implications (there are attacks that work only if the server allows for GET). POST will not get cached.
If you are using IE 9, then you need to use the following in front of your controller class definition:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class TestController : Controller
This will prevent the browser from caching.
Details on this link: http://dougwilsonsa.wordpress.com/2011/04/29/disabling-ie9-ajax-response-caching-asp-net-mvc-3-jquery/
Actually this solved my issue.