jQuery in Action
Taking full control of an Ajax request
253
dataType: 'html',
error: function(xhr) {
$('#errorDisplay)
.html('Error: ' + xhr.status + ' ' + xhr.statusText);
}
})
This would ensure that every subsequent Ajax call (again, except via
load()
)
would use these defaults, unless explicitly overridden in the properties passed to
the Ajax utility function being used. Note the defaulting of an
the Ajax utility function being used. Note the defaulting of an
error
callback. It's
quite common for
error
,
complete
, and even
beforeSend
callbacks that should be
applied to all Ajax invocations to be specified in this way.
Now, what about those global functions that were controlled by the
global
property?
8.4.3 Global functions
In addition to the ability to specify default functions to be executed for all Ajax
requests by establishing them as defaults with
requests by establishing them as defaults with
$.ajaxSetup()
, jQuery also allows
us to attach functions to specific
DOM
elements. These functions will be triggered
during the various phases of Ajax request processing or when a request ultimately
succeeds or fails.
succeeds or fails.
For example, to attach a function to an element with an
id
of
errorConsole
whose purpose is to display error messages, we write
$('#errorConsole').ajaxError(reportError);
The function
reportError
will be called in the event that any Ajax request fails.
When this, or any other of these global functions, is invoked, the first param-
eter passed to the callback function consists of a JavaScript
Object
instance with
the following two properties:
type
--A string that contains the type of global function invoked--ajax-
Error, for example.
target
--A reference to the
DOM
element to which the global function was
attached. In the case of the previous example, it's the element with the
id
of
errorConsole
.
We'll call this construct the Global Callback Info object. Some global function types
are passed additional parameters (as we'll see shortly), but this common first
parameter can be used to identify what global function type triggered the call-
back and to which element the function was attached.
are passed additional parameters (as we'll see shortly), but this common first
parameter can be used to identify what global function type triggered the call-
back and to which element the function was attached.
The commands that can be used to attach these global functions are
ajax-
Start()
,
ajaxSend()
,
ajaxSuccess()
,
ajaxError()
,
ajaxComplete()
, and
ajaxStop()
.