jQuery in Action
Taking full control of an Ajax request
257
This establishes a function that will be called when an Ajax request completes suc-
cessfully. This callback is passed a Global Callback Info instance whose target
identifies the bound element--in this case,
cessfully. This callback is passed a Global Callback Info instance whose target
identifies the bound element--in this case,
successDisplay
. We use that reference
to construct a success message and display it in the success display area.
The binding of the error callback is similar.
$('#errorDisplay').ajaxError(function(info,xhr){
$(info.target)
.append('<div>Failed at '+new Date()+'</div>')
.append('<div>Status: ' + xhr.status + ' ' +
xhr.statusText+'</div>');
});
Using the
ajaxError()
command, we bind a callback function that will be invoked
when an Ajax request fails. In this case, the
XHR
instance is passed to the func-
tion, and we use it to give the user information about the nature of the error.
Because each function is bound to only one global function type, the use of the
type
field of the Global Callback Info instance isn't needed. But notice how the two
functions perform some similar processing? How can we combine these functions
into a single function instance that uses the
into a single function instance that uses the
type
field to operate more efficiently?
With the page displayed in the browser, click each button a number of times
(the messages have timestamps, so it's easy to discern the order in which they are
displayed). You might end up with a display such as shown in figure 8.8.
displayed). You might end up with a display such as shown in figure 8.8.
Figure 8.8 Clicking the buttons reveals how the callback functions get information
and how they know which element they are attached to.
and how they know which element they are attached to.