Information Technology Reference
In-Depth Information
In this function, we first test to see what the readyState and status are of our request.
The former can return five different numbers, which correspond to where the request is
in terms of processing. Returning a code of
0 means that the request hasn't been started yet. This is the state in
which a new request would be before being sent.
1 means that the connection to the server has been initialized. In
essence, the pipe is open, and data is moving.
2 or 3 means that the request has been sent and is processing,
respectively. At this point, all your code can do is sit and wait (or show
a “loading” graphic, if you so choose).
4 means that the request is complete and ready for the code. You can
now do whatever you want to do with the information.We only want to
change the text on the page once we reach a readyState of 4.
We also care about the status , which can report 200 (for “OK”) or 404 (for “not found”).
So the second line of Listing 12-3 translates to: “Only do this if the request is ready and
it was done successfully!” From there, it's simply one line that changes the ellipsis, or
text placeholder (see Listing 12-4), to the text that was returned by the request.
Finishing up Listing 12-3, we're creating and sending our request. The line starting
request.open calls the function that specifies what we're trying to retrieve and how we
want to do it. In this case, it's a really simple request—we're just getting data, not
sending any data we want the server to parse. We'll use the “GET” method instead of
“POST” because it's faster, we'll ask for “ word.txt ,” and we'll set asynchronous to
“true,” since we want the response in the background, allowing the script to continue
running. For a discussion of why we might set this to false, as well as more detail on
GET versus POST methods, see the end of this chapter in the “AJAX Considerations”
section.
Finally, we simply call request.send() , which fires off our request. Once we get the
request back, the XMLHttpRequest object will fire our onreadystatechange and change
the line in the webpage.
Finally we finish the page off in Listing 12-4 by creating the basic HTML structure.
We've got a special div id called “theword” which holds an ellipsis (…) to begin with.
This is what will be replaced by the JavaScript code we wrote at the top. We have a
button as well, which fires off our function, loadword() .
Listing 12-4. word.html, Part 3: The Rest of the Page, Consisting of a Simple Body Portion and Text, Along with
'theword' div
</head>
<body>
<span style="font-family: Helvetica,Arial,sans-serif;">Get Today's Word
Of The Day<br>
<div id="theword">
<h2>...</h2>
</div>
<button type="button" onclick="loadword()">Get The Word!</button>
 
Search WWH ::




Custom Search