AJAX - The Complete Reference

(avery) #1

PART II


Chapter 6: Networking Considerations 271


been to make sure that the browser does not cache these requests. There are three methods
to use in order to keep the browser from caching the requests.

Emit No Caching Headers from the Server Side
As seen since the very first example in Chapter 1, when using Ajax it is often important to
keep the browser from caching a request. Cache control can easily be accomplished by
emitting response headers on the server. As an example, in PHP, use statements like:

header("Cache-Control: no-cache");
header("Pragma: no-cache");

to emit the proper cache control headers. There are many types of headers that can be used
to control caching and it is possible to be quite verbose in your responses. Here, for
example, are a few headers seen coming from one Ajax-powered site:

Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

Apparently the person who built this application really doesn’t want to cache anything!

Make Requests with Unique URLs
A common way to bust a cache is to make the URL different each time in a way that does not
affect the actual request. For example, say the script was calling a program hello.php that
returned some varying message. Because the URL would be the same on subsequent
requests, you might worry it would be cached and thus the user won’t see the new message.
To make it unique, the script can just append a query string like so: http://ajaxref.com/ch6/
hello.php?ts=unique-value. A simple way to do this would be to use a time stamp like so:

var url = "http://ajaxref.com/ch6/hello.php";
var payload = "";
payload = "ts=" + (new Date()).getTime();
var options = { method: "GET",
outputTarget : "responseOutput",
payload:payload
};
AjaxTCR.comm.sendRequest(url,options);

While this method isn’t built in to the library, it is easily enough implemented as just shown.
We opted not to implement it natively because it dirties the URL while the next method
does not and accomplishes the same goal.

Make Requests with Old If-Modified-Since Header
In the library, it is possible to set an option value of preventCache to true, and it will send
a request header of If-Modified-Since with a date in the past so that the request will
assume that it needs to be refetched.

/* Prevent Caching if set */
if (request.preventCache)
request.xhr.setRequestHeader("If-Modified-Since", "Wed, 15 Nov 1995 04:58:08 GMT");
Free download pdf