In this article, you will learn how to use AJAX for reading and manipulating simple XML files, in order to implement a basic Web service. Specifically, you will learn how to develop a JavaScript application that fetches data from an XML file. By the end of this article, you will know the basics for using client-side parsed XML in your own applications.
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:
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.