JavaScript Remote Scripting: Processing XML Files - Checking the progress of a request: a quick look at the “stateChecker()” function
(Page 4 of 6 )
If you’re used to writing JavaScript functions that verify the status of http requests, then the “statusChecker()” function should be pretty straightforward. First off, let’s see how it looks and then discuss its logic:
function stateChecker(){
// if request is completed
if(xmlobj.readyState==4){
// if status == 200 display text file
if(xmlobj.status==200){
// create data container
createDataContainer();
// read XML data
data=xmlobj.responseXML.getElementsByTagName('message');
// display XML data
displayData();
}
else{
alert('Failed to get response :'+ xmlobj.statusText);
}
}
}
With reference to the function above, its logic can be explained through two simple steps. Of course, the first one involves checking the request’s status by verifying the values of both “readyState” and “status” properties. Once the request has been successfully completed, the second step takes place. Notice that the code calls the “createDataContainer()” function, which is tasked with building the required (X)HTML structure for displaying headlines. However, let’s pause for a moment and pay attention to the following line:
data=xmlobj.responseXML.getElementsByTagName('message');
What this line of code does is simply store in the “data” array all the “<message>” nodes defined within the XML file that you saw previously, by applying the “getElementsByTagName()” method to the “responseXML” property. In a nutshell, this expression shows how easy it is to fetch XML data, by utilizing only DOM methods.
As you can see, the rest of the functions are fairly straightforward. After reading and storing all the “<message>” nodes in an array structure, the only thing left to be done is display the appropriate headlines. As you’ll see shortly, this operation is performed by the “displayData()” function.
Next: Displaying XML data: defining the “createDataContainer()” and “displayData()” functions >>
More JavaScript Articles
More By Alejandro Gervasio