AJAX - The Complete Reference

(avery) #1

462 Part II: Developing an Ajax Library^


that will be used to set the current window’s title once the request has happened, and a
saveResponse Boolean so that the response returned is cached. By default, it is set to
false, so as the user moves through the history, it will re-request the URL in question
rather than using the stored response. Here is a simple example:

historyObject = { id : "Baltar",
title : "Caprica Ministry of Science",
saveResponse : true };

Now with this history object in hand, simply make a request as normal and specify the
history : historyObject in the options object.

var url = "http://ajaxref.com/ch9/hello.php";
var options = { method: "GET",
payload: payload,
history: historyObject,
onSuccess: showResponse};

This will pretty much solve the history problems, but how exactly does it work? Well,
when the request is made in sendRequest() if the response is not being saved, the
AjaxTCR.history.addToHistory() method is called immediately:

if (request.history && !request.history.saveResponse)
AjaxTCR.history.addToHistory(request.history.id, "",
request.history.title, url, options);

You’ll note that we pass the hash mark id value, the title we want to change the page
to, and the data to make the request again later, namely the URL and the request options.
You might wonder what the blank value is. This is data that could be passed to a callback
function if this were performed manually rather than through an Ajax request.
If the response is being saved, the history addition would happen, not in the
sendRequest() method but in the _handleResponse() method, and it would include the
response data itself rather than the URL and options necessary to repeat the request.

if (response.history && response.history.saveResponse)
AjaxTCR.history.addToHistory(response.history.id, "",
response.history.title, "", response);

In either case, addToHistory( )is invoked, which has a method signature like so:

addToHistory : function(key, data, title, url, options){ }

where key is the key to store the history item under, data is the data field to be returned to
the callback function, title is the string to change the page title to, url is the URL to
request, and options is the options for that request.
The first step in this method is to look at the passed key and see if it indicates the initial
state. If it doesn’t, the hash value is set in the URL to the key which is normally encoded
though allowing “/” characters. The private property _currentState that corresponds to
the hashed key is also updated.
Free download pdf