jQuery in Action

Brushing up on Ajax
223
firing simultaneously. Luckily, we shall see that the jQuery Ajax
API
handily solves
this problem for us.
Let's explore how to deal with the response from a completed request.
8.1.4 Getting the response
Once the ready handler has determined that the
readyState
is complete and that
the request completed successfully, the body of the response can be retrieved
from the
XHR
instance.
Despite the moniker Ajax (where the X stands for
XML
), the format of the
response body can be any text format; it's not limited to
XML
. In fact, most of
the time, the response to Ajax requests is a format other than
XML
. It could be
plain text or, perhaps, an
HTML
fragment; it could even be a text representation
of a JavaScript object or array in JavaScript Object Notation (
JSON
) format.
Regardless of its format, the body of the response is available via the
response-
Text
property of the
XHR
instance (assuming that the request completes suc-
cessfully). If the response indicates that the format of its body is
XML
by including
a content-type header specifying a
MIME
type of text/xml (or any
XML
MIME
type),
the response body will be parsed as
XML
. The resulting
DOM
will be available in
the
responseXML
property. JavaScript (and jQuery itself, using its selector
API
) can
then be used to process the
XML
DOM
.
Processing
XML
on the client isn't rocket science, but--even with jQuery's
help--it can still be a pain. Although there are times when nothing but
XML
will
do for returning complex hierarchical data, frequently page authors will use
other formats when the full power (and corresponding headache) of
XML
isn't
absolutely necessary.
But some of those other formats aren't without their own pain. When
JSON
is
returned, it must be converted into its runtime equivalent. When
HTML
is returned,
it must be loaded into the appropriate destination element. And what if the
HTML
markup returned contains
<script>
blocks that need evaluation? We're
not going to deal with these issues in this section because it isn't meant to be a
complete Ajax reference and, more importantly, because we're going to find out
that jQuery handles most of these issues on our behalf.
A diagram of this whole process is shown in figure 8.1.
In this short overview of Ajax, we've identified the following pain points that
page authors using Ajax need to deal with:



Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.