AJAX - The Complete Reference

(avery) #1

PART II


Chapter 5: Developing an Ajax Library 223


Scriptaculous Effects
Because of the many helper functions built into Prototype, many developers prefer to start
with it as their base. This has led to the creation of many Prototype add-on libraries. The
most popular of these is script.aculo.us, which is built on top of Prototype. At this point in
time, you simply cannot use script.aculo.us without Prototype. Where Prototype has many
features to make programmers happy, script.aculo.us has many features to make Web users
happy. It is full of pure JavaScript effects that make using Ajax (and JavaScript) more fun,
responsive, and Web 2.0ish. You can see a simple example at http://ajaxref.com/ch5/
prototypescriptaculous.html and now you will be greeted with a bit more pizzazz. We’ll see
another use of such effects in Chapter 8 when we look at the use of transitions.

Introduction to jQuery


The jQuery library aims to be a small, high speed library that provides tremendous
improvement in DOM traversal, event management, and, of course, Ajax. The jQuery
(www.jquery.com) site makes a fairly boastful claim that the library “...is designed to
change the way that you write JavaScript,” and that you will be able to write less code that
does more. However, once you spend some time with jQuery, you might see that these
claims may not be that outrageous. Of course, we initially focus on the Ajax support in the
library before turning your attention to its other aspects.

jQuery’s Approach to Ajax

The most primitive form of Ajax access that jQuery currently provides is via the
$.ajax(options) method. Similar to other libraries, this method takes a single object of a
variety of options to configure the request list in Table 5-11. Most of these are expected and
don’t really add too much to the state of the art in Ajax request management.
As an illustration of jQuery’s basic Ajax syntax, to make a simple GET request to the
“Hello World” example from Chapter 1, we set a few options and then invoke $.ajax()
like so:

var options = {success : handleResponse,
type : "GET",
url : "http://ajaxref.com/ch1/sayhello.php"
}
var request = $.ajax(options);

Notice The method returns a value that is simply a reference to the created
XMLHttpRequest object. It is not necessary to save this value, but if you desire to control
requests such as using the abort() method, it is required. If this last point makes the XHR
wrapper feel incomplete, you aren’t misinterpreting the analysis. To bolster this opinion,
note that as of version 1.1.3.1, no jQuery-native way to set request headers can be found. It
would be required to set the beforeSend property to some function and then use raw XHR
methods as shown by this simple example:

beforeSend : function (xhr){xhr.setRequestHeader("X-JS-Lib","jQuery"); },
Free download pdf