Wednesday, 28 May 2008

Ajax: Caching Problem with Requests

http://radio.javaranch.com/pascarello/2005/10/21/1129908221072.html

"The question: The Ajax request is grabbing the cached page from the previous request, how do I stop this from happening?
Well I have seen some fancy approaches by people, but there is one easy solution that works: a random query string value appended to the request.

So how and why does this work. Well it simple terms, when the browser looks at the destination, if it has a match, then it uses the data it has. Now this is great for when you are going to a static website, but since we are looking for new data, it sucks. By appending a random value to our parameters that we are sending back, it forces the browser to say, "Stop the press! We got new info here! Lets go get the data!"

"... a simple "+Date()" appended to the request URL and viola!"

OR

"Hey guys, just wanted to add a way to ad this random string to the URL. When passing the url you can append the random function Math.random(); to the url string like this: var urlVar = urlVar + '&' + Math.random();"

OR

"A much more elegant solution would be to use the following code:

xmlhttp.open("GET", theURL ,true);
xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
xmlhttp.send();

The second line of the code instructs the XMLHttp object to avoid
caching content that has been modified after the mentioned date.
It worked fine for me..."

No comments: