Chapter 5 — How Gmail Works 59
The first line defines the name of the function:Listing1.
The second line sets up the openmethod of the XMLHttpRequestfunction
you’ve placed into the xmlhttpobject.XMLHttpRequesthas six possible methods
to call, as you’ll see later. The openmethod takes three parameters: the HTTP
call (such as GETor POST), the URL, and a flag of trueor falseto indicate if
the request is asynchronous (set to true) or not (set to false). Asynchronous in
this context means that the script continues processing while it is waiting for the
server to reply. In this listing it’s not a big deal, but in others this is very impor-
tant: If you set the request to false, and the server takes a long time to get back to
you, you can lock up the browser in the meantime.
The third line solves this problem. It sets up an onreadystatechangeevent
handler, which waits for the XMLHttpRequestfunction’s state to change before
running the function it has defined. The possible values for onreadystate
changeare in Table 5-2, but in the meantime know that readyState=4means
that the XMLHttpRequestfunction has completed its task. So, lines 3 and 4 mean
“Wait until the function’s state has changed, and if the state has changed to ‘com-
plete’ then do the following; if not, keep waiting.”
Line 5 is triggered if 3 and 4 come true. It displays an alert box, containing the
result of the responseTextmethod. This contains the contents of Listing.txt.
Lines 6 and 7 close off the functions prettily, and line 8 triggers the communica-
tion itself. Note the order this all comes in: You’ve set up the request ready to go.
You’ve set up an Event Handler, watching for any request to come back and say
it’s done, and only then do you fire off the request itself.
So, now you’ve got a page with JavaScript code that can go out, fetch another file,
and do something with its contents, all without refreshing the HTML. In our
listing, it’s a file with plain text, but it can be just about anything: XML, for
example.
Before moving on to using this new knowledge to look into Gmail’s code, have a
look at Tables 5-1 and 5-2, which serve as a reference of the XMLHttpRequest
functions, methods, and suchlike.
Table 5-1 XMLHttpRequest Object Methods
Method Description
abort() Stops the current request.
getAllResponseHeaders() Returns complete set of headers (labels and
values) as a string.
Continued