Bypass caching with jQuery AJAX GET requests
As I seem to use this trick quite often and I keep forgetting the exact details on how to implement it, I thought it would be good to document this.
Using jQuery, I often make ansynchronous GET requests to a custom ASHX handler in SharePoint’s _layouts folder which returns some data that I want to display. This data is always dynamic, but sometimes the browser tries to cache the results from the previous request, so you might not get the response you expected.
To avoid this, simply make the url for eacht request unique by adding a timestamp to it in javascript.
var url = '/_layouts/MyProject/MyHandler.ashx?unique=' + new Date().getTime();
Adding the timestamp to a url reliably gets around caching. But it doesn’t hurt to further bullet proof by disable caching–if that’s what you want to do–in the ProcessRequest method of your IHttpHandler implementation.
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetNoStore();
context.Response.Cache.SetExpires(DateTime.MinValue);
context.Response.Expires = -1;
// rest of your code here
// …
}
anonymous
February 18, 2011 at 8:31 pm