72
however, so the response can usually be ignored in this case). For other types, the
response is simply the text of the requested resource.
The second argument status code is normally the string “success”, but if you have
set the
ifModified
option, this argument might be “notmodified” instead. In this
case, the server does not send a response and the first argument is undefined. Cross-
domain requests of type “script” and “jsonp” are performed with a
<script>
ele-
ment instead of an XMLHttpRequest, so for those requests, the third argument
will be undefined.
error
This option specifies the callback function to be invoked if the Ajax request does
not succeed. The first argument to this callback is the XMLHttpRequest object of
the request (if it used one). The second argument is the jQuery status code. This
may be “error” for an HTTP error, “timeout” for a timeout, and “parsererror” for
an error that occurred while parsing the server’s response. If an XML document or
JSON object is not well-formed, for example, the status code will be “parsererror”.
In this case, the third argument to the
error
callback will be the Error object that
was thrown. Note that requests with
dataType
“script” that return invalid Java-
Script code do not cause errors. Any errors in the script are silently ignored, and
the
success
callback is invoked instead of the
error
callback.
complete
This option specifies a callback function to be invoked when the Ajax request is
complete. Every Ajax request either succeeds and calls the
success
callback or fails
and calls the
error
callback. jQuery invokes the
complete
callback after invoking
either
success
or
error
. The first argument to the
complete
callback is the
XMLHttpRequest object, and the second is the status code.
19.6.3.3 Uncommon options and hooks
The following Ajax options are not commonly used. Some specify options that you are
not likely to set and others provide customization hooks for those who need to modify
jQuery’s default handling of Ajax requests.
async
Scripted HTTP requests are asynchronous by their very nature. The
XMLHttpRequest object provides an option to block until the response is received,
however. Set this option to
false
if you want jQuery to block. Setting this option
does not change the return value of
jQuery.ajax()
: the function always returns the
XMLHttpRequest object, if it used one. For synchronous requests, you can extract
the server’s response and HTTP status code from the XMLHttpRequest object
yourself, or you can specify a
complete
callback (as you would for an asynchronous
request) if you want jQuery’s parsed response and status code.
dataFilter
This option specifies a function to filter or preprocess the data returned by the
server. The first argument will be the raw data from the server (either as a string or
568 | Chapter 19: The jQuery Library
77
Document object for XML requests) and the second argument will be the value of
the
dataType
option. If this function is specified, it must return a value, and that
value will be used in place of the server’s response. Note that the
dataFilter
func-
tion is invoked before JSON parsing or script execution is performed. Also note
that
dataFilter
is not invoked for cross-origin “script” and “jsonp” requests.
jsonp
When you set the
dataType
option to “jsonp”, your
url
or
data
option usually
includes a parameter like “jsonp=?”. If jQuery does not find such a parameter in
the URL or data, it inserts one, using this option as the parameter name. The default
value of this option is “callback”. Set this option if you are using JSONP with a
server that expects a different parameter name and have not already encoded that
parameter into your URL or data. See §18.2 for more about JSONP.
jsonpCallback
For requests with
dataType
“jsonp” (or type “json” when the URL includes a JSONP
parameter like “jsonp=?”), jQuery must alter the URL to replace the question mark
with the name of the wrapper function that the server will pass its data to. Nor-
mally, jQuery synthesizes a unique function name based on the current time. Set
this option if you want to substitute your own function for jQuery’s. If you do this,
however, it will prevent jQuery from invoking the
success
and
complete
callbacks
and from triggering its normal events.
processData
When you set the
data
option to an object (or pass an object as the second argument
to
jQuery.get()
and related methods), jQuery normally converts that object to a
string in the standard HTML “application/x-www-form-urlencoded” format (see
the sidebar in §19.6.2.2). If you want to avoid this step (such as when you want to
pass a Document object as the body of a POST request), set this option to
false
.
scriptCharset
For cross-origin “script” and “jsonp” requests that use a
<script>
element, this
option specifies the value of the
charset
attribute of that element. It has no effect
for regular XMLHttpRequest-based requests.
traditional
jQuery 1.4 altered slightly the way that data objects were serialized to “application/
x-www-form-urlencoded” strings (see the sidebar in §19.6.2.2 for details). Set this
option to
true
if you need jQuery to revert to its old behavior.
username
,
password
If a request requires password-based authentication, specify the username and
password using these two options.
xhr
This option specifies a factory function for obtaining an XMLHttpRequest. It is
invoked with no arguments and must return an object that implements the
XMLHttpRequest API. This very low-level hook allows you create your own wrap-
per around XMLHttpRequest, adding features or instrumentation to its methods.
19.6 Ajax with jQuery | 569
Client-Side
JavaScript
71
19.6.4 Ajax Events
§19.6.3.2 explained that
jQuery.ajax()
has four callback options:
beforeSend
,
success
,
error
, and
complete
. In addition to invoking these individually specified callback func-
tions, jQuery’s Ajax functions also fire custom events at each of the same stages in a
Ajax request. The following table shows the callback options and the corresponding
events:
Callback
Event Type
Handler Registration Method
beforeSend
“ajaxSend”
ajaxSend()
success
“ajaxSuccess”
ajaxSuccess()
error
“ajaxError”
ajaxError()
complete
“ajaxComplete”
ajaxComplete()
“ajaxStart”
ajaxStart()
“ajaxStop”
ajaxStop()
You can register handlers for these custom Ajax events using the
bind()
method
(§19.4.4) and the event type string shown in the second column or using the event
registration methods shown in the third column.
ajaxSuccess()
and the other methods
work just like the
click()
,
mouseover()
, and other simple event registration methods
of §19.4.1.
Since the Ajax events are custom events, generated by jQuery rather than the browser,
the Event object passed to the event handler does not contain much useful detail. The
ajaxSend, ajaxSuccess, ajaxError, and ajaxComplete events are all triggered with ad-
ditional arguments, however. Handlers for these events will all be invoked with two
extra arguments after the event. The first extra argument is the XMLHttpRequest object
and the second extra argument is the options object. This means, for example, that a
handler for the ajaxSend event can add custom headers to an XMLHttpRequest object
just like the
beforeSend
callback can. The ajaxError event is triggered with a third extra
argument, in addition to the two just described. This final argument to the event han-
dler is the Error object, if any, that was thrown when the error occurred. Surprisingly,
these Ajax events are not passed jQuery’s status code. If the handler for an ajaxSuccess
event needs to distinguish “success” from “notmodified”, for example, it will need to
examine the raw HTTP status code in the XMLHttpRequest object.
The last two events listed in the table above are different from the others, most obviously
because they have no corresponding callback functions, and also because they are trig-
gered with no extra arguments. ajaxStart and ajaxStop are a pair of events that indicate
the start and stop of Ajax-related network activity. When jQuery is not performing any
Ajax requests and a new request is initiated, it fires an ajaxStart event. If other requests
begin before this first one ends, those new requests do not cause a new ajaxStart event.
The ajaxStop event is triggered when the last pending Ajax request is completed and
jQuery is no longer performing any network activity. This pair of events can be useful
570 | Chapter 19: The jQuery Library
75
to show and hide some kind of “Loading...” animation or network activity icon. For
example:
$("#loading_animation").bind({
ajaxStart: function() { $(this).show(); },
ajaxStop: function() { $(this).hide(); }
});
These ajaxStart and ajaxStop event handlers can be bound to any document element:
jQuery triggers them globally (§19.4.6) rather than on any one particular element. The
other four Ajax events, ajaxSend, ajaxSuccess, ajaxError, and ajaxComplete, are also
normally triggered globally, so you can bind handlers to any element. If you set the
context
option in your call to
jQuery.ajax()
, however, these four events are triggered
on the context element rather than globally.
Finally, remember that you can prevent jQuery from triggering any Ajax-related events
by setting the
global
option to
false
. Despite its confusing name, setting
global
to
false
stops jQuery from triggering events on a
context
object as well as stopping jQuery
from triggering events globally.
19.7 Utility Functions
The jQuery library defines a number of utility functions (as well as two properties) that
you may find useful in your programs. As you’ll see in the list below, a number of these
functions now have equivalents in ECMAScript 5 (ES5). jQuery’s functions predate
ES5 and work in all browsers. In alphabetical order, the utility functions are:
jQuery.browser
The
browser
property is not a function but an object that you can use for client
sniffing (§13.4.5). This object will have the property
msie
set to
true
if the browser
is IE. The
mozilla
property will be true if the browser is Firefox or related. The
webkit
property will be true for Safari and Chrome, and the
opera
property will be
true for Opera. In addition to this browser-specific property, the
version
property
contains the browser version number. Client sniffing is best avoided whenever
possible, but you can use this property to work around browser-specific bugs with
code like this:
if ($.browser.mozilla && parseInt($.browser.version) < 4) {
// Work around a hypothetical Firefox bug here...
}
jQuery.contains()
This function expects two document elements as its arguments. It returns
true
if
the first element contains the second element and returns
false
otherwise.
jQuery.each()
Unlike the
each()
method which iterates only over jQuery objects, the
jQuery.each()
utility function iterates through the elements of an array or the
properties of an object. The first argument is the array or object to be iterated.
19.7 Utility Functions | 571
Client-Side
JavaScript
80
The second argument is the function to be called for each array element or object
property. That function will be invoked with two arguments: the index or name of
the array element or object property, and the value of the array element or object
property. The
this
value for the function is the same as the second argument. If
the function returns
false
,
jQuery.each()
returns immediately without completing
the iteration.
jQuery.each()
always returns its first argument.
jQuery.each()
enumerates object properties with an ordinary
for/in
loop, so all
enumerable properties are iterated, even inherited properties.
jQuery.each()
enu-
merates array elements in numerical order by index and does not skip the undefined
properties of sparse arrays.
jQuery.extend()
This function expects objects as its arguments. It copies the properties of the second
and subsequent objects into the first object, overwriting any properties with the
same name in the first argument. This function skips any properties whose value
is
undefined
or
null
. If only one object is passed, the properties of that object are
copied into the
jQuery
object itself. The return value is the object into which prop-
erties were copied. If the first argument is the value
true
, a deep or recursive copy
is performed: the second argument is extended with the properties of the third (and
any subsequent) objects.
This function is useful for cloning objects and for merging options objects with
sets of defaults:
var clone = jQuery.extend({}, original);
var options = jQuery.extend({}, default_options, user_options);
jQuery.globalEval()
This function executes a string of JavaScript code in the global context, as if it were
the contents of a
<script>
element. (In fact, jQuery actually implements this func-
tion by creating a
<script>
element and temporarily inserting it into the document.)
jQuery.grep()
This function is like the ES5
filter()
method of the Array object. It expects an
array as its first argument and a predicate function as its second, and it invokes the
predicate once for each element in the array, passing the element value and the
element index.
jQuery.grep()
returns a new array that contains only those elements
of the argument array for which the predicate returned
true
(or another truthy
value). If you pass
true
as the third argument to
jQuery.grep()
, it inverts the sense
of the predicate and returns an array of elements for which the predicate returned
false
or another falsy value.
jQuery.inArray()
This function is like the ES5
indexOf()
method of the Array object. It expects an
arbitrary value as its first argument and an array (or array-like object) as its second
and returns the first index in the array at which the value appears, or -1 if the array
does not contain the value.
572 | Chapter 19: The jQuery Library
Documents you may be interested
Documents you may be interested