jQuery in Action

222
CHAPTER 8
Talk to the server with Ajax
An example of such a call is as follows:
xhr.send('a=1&b=2&c=3');
Now let's see what the ready handler is all about.
8.1.3 Keeping track of progress
An
XHR
instance informs us of its progress through the ready state handler. This
handler is established by assigning a reference to the function to serve as the
ready handler to the
onreadystatechange
property of the
XHR
instance.
Once the request is initiated via the
send()
method, this callback will be
invoked numerous times as the request makes transitions through its various
states. The current state of the request is available as a numeric code in the
readyState
property (see the description of this property in table 8.1).
That's nice, but more times than not, we're only interested in when the request
completes and whether it was successful or not. So frequently, we'll see ready han-
dlers implemented using the pattern shown in listing 8.2.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status >= 200 &&
xhr.status < 300) {
//success
}
else {
//error
}
}
}
This pattern ignores all but the completed state and, once complete, examines
the value of the
status
property to determine if the request succeeded or not.
The
HTTP
Specification defines all status codes in the 200 to 299 range as success
and those with values of 300 or above as various types of failures.
We should note one thing about this ready handler; it referenced the
XHR
instance through a top-level variable. But shouldn't we expect the instance to be
passed to the handler as a parameter?
Well, we could have expected that, but that's not what happens. The instance
must be located by some other means, and that's usually a top-level (global)
Listing 8.2
Writing the ready state handler to ignore all but the completed state
Ignores all but
completed state
Branches on
response status
Executes on
success
Executes
on failure


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

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