Information Technology Reference
In-Depth Information
if (window.XMLHttpRequest){
// Modern browsers use this type of request
request =new XMLHttpRequest();
}else{
// Old Microsoft browsers use this type!
request =new ActiveXObject("Microsoft.XMLHTTP");
}
OK, we're up and running. The first thing we did was create the top of a standard HTML
page, and then started a new JavaScript function named loadword , which will do most
of the heavy lifting of the page. Inside this function, we first need to figure out if we're
using a modern browser (i.e., something released in the last five years, like Firefox,
Safari, Opera, Chrome, or newer versions of Internet Explorer) or an older Microsoft
browser (Internet Explorer 5 or 6). The reason for this is simple: Older Microsoft
browsers don't know what an XMLHttpRequest() object is! For them, we'll ask that an
ActiveX object be created, which will give us the same functionality. It's just a funny
compromise to the way Microsoft used to code browsers. Let's continue working with
the JavaScript for this page in Listing 12-3.
Listing 12-3. word.html, Part 2: The JavaScript onreadystatechange Function, and the End of the JavaScript
Block
request.onreadystatechange=function() {
if ( request.readyState == 4 &&request.status == 200){
document.getElementById("theword").innerHTML = request.responseText;
}
}
request.open("GET","word.txt",true);
request.send();
}
</script>
Now that we have our request object, named aptly “ request ,” we can ask it to do some
things. This next part of the code is written slightly “backward,” in that the code written
at the top will be executed after the code written at the bottom. This is because the
XMLHttpRequest object, the heart of AJAX, has a special function named
onreadystatechange . Anytime the request we're making, processing in the background,
does something either expected or unexpected, it fires this function. In essence, this
function is where we put the “what do I do with what I get back” code. You can think of
the code here as the programming equivalent of “substitute teacher's instructions.” You
may remember, as an astute student, that when your teacher was absent, he or she
would leave instructions for the replacement, perhaps in a special folder. Your
onreadystatechange function acts as those instructions, telling the computer (in this
case, the JavaScript engine) what to do when you're not around but something
happens. Most of the time, these instructions are similar to what we have preceding (in
this case, “if the request is processed correctly, display it on the screen”). We can also
include instructions for “worst case scenarios,” such as when the request cannot be
fulfilled, or it throws an error.
 
Search WWH ::




Custom Search