AJAX - The Complete Reference

(avery) #1

182 Part II: Applied Ajax^


There are many more values to cover, but the goal here is to study them piecemeal, so
we focus first on those required for introduction. The user is often going to set many of
these values themselves, as well as add other values. For example, assume that a user may
define options, like so:

var url = "http://ajaxref.com/ch3/setrating.php";
var options = { method: "GET",
payload : "foo=bar&example=true",
preventCache : true,
magicNumber : 2585
};

AjaxTCR.comm.sendRequest(url,options);

In the sendRequest() method, any values passed in by the user would override the
defaults.

/* apply options defined by user */
for (option in options)
request[option] = options[option];

The user is free to define any properties they like. For example, in the sample options
shown, the value named magicNumber will be added to the request and then it will be
available in the various callbacks that are invoked, which should cut down on any desire to
use global variables.
Note the inclusion of a payload string in the simple example. Given what was discussed
in Chapter 4 about how sloppy people can be with payload variables, the library includes
helpful utilities, such as the encodeValue() function, which address all the small oversights
with JavaScript’s native encodeURIComponent() and escape() methods. However, a new
child object namespace called data is created which is where all useful data handling routines
will be encapsulated. To invoke this method, you use AjaxTCR.data.encodeValue() as
shown here:

var payload = "rating=" + AjaxTCR.data.encodeValue(rating);

Now with the payload defined, encoded, and—hopefully—passed properly, the library
decides how to send it. In the case of a GET request, the query string of the passed in URL
must be formed; in the case of POST, the postBody property of our request object is set.

/* address payload depending on method */
if (request.method.toUpperCase() == "GET")
request.url = url + "?" + request.payload;
else
request.url = url;

if (request.method.toUpperCase() == "POST")
request.postBody = request.payload;
else
request.postBody = null;
Free download pdf