58 Part II — Getting Inside Gmail
What has happened here? Well, the link in the code doesn’t go anywhere, but
clicking it sets the JavaScript going. Have a look at the first half of the code again:
<script type=”text/javascript”>
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try {
xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!=’undefined’) {
xmlhttp = new XMLHttpRequest();
}
Stepping through this from the beginning, you set up a variable called xmlhttp
and set it to false. You use this variable to help check which browser you’re using.
The XMLHttpRequestobject is called different things in different applications
(Technically speaking, it’s not a standard part of the JavaScript specification, so
different people call it different things. Ho hum.). In Microsoft browsers, it’s an
Active X object called Msxml2.XMLHTTPor Microsoft.XMLHTTP, whereas in
Mozilla, Safari, and others, it’s a standard JavaScript function called
XMLHttpRequest.
So the first half of the code goes through the alternatives, trying to define xml-
httpas an XMLHttpRequestobject by calling each of the possible functions in
turn. First it tries Msxml2.XMLHTTP, then Microsoft.XMLHTTP, and finally
defaults to XMLHttpRequest. (Usually, of course, there’s another test for no-
JavaScript-support-at-all, but we’ll skip that here for the sake of brevity.)
Now, go line by line through the second half of the code:
function Listing1() {
xmlhttp.open(“GET”, “Listing.txt”,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
}
xmlhttp.send()
}