JavaScript Remote Scripting: Processing XML Files

来源:百度文库 编辑:神马文学网 时间:2024/04/28 23:55:43
http://www.devarticles.com/c/a/JavaScript/JavaScript-Remote-Scripting-Processing-XML-Files/
JavaScript Remote Scripting:Processing XML Files
(Page 1 of 6 )
In this article, you will learn how to use AJAX forreading and manipulating simple XML files, in order to implement abasic Web service. Specifically, you will learn how to develop aJavaScript application that fetches data from an XML file. By the endof this article, you will know the basics for using client-side parsedXML in your own applications.Here you have it. Welcome to thesecond part of the series “JavaScript Remote Scripting.” Based on thetheoretical concepts explained in the first tutorial, as well as theirapplication in an illustrative example, I’ve demonstrated how to readfile data from the server by using AJAX as the primary method formaking http requests in the background, without having to reload thecurrent page.
Stepping back for a moment to the scriptthat I previously developed in the first article, it implements asimple mechanism for fetching data from a plain text file anddisplaying the information through a predefined sequence. Although theexample is rather basic, it does exposes the foundations of AJAXtechnology for building more complex and polished applications, byutilizing as core programming logic the powerful capabilities forsending silent http requests on the fly.
The best thingwith this approach is that it offers a broad range of applications forfetching data from the server in multiple formats. Of course you havealready seen how easy it is to fetch data from flat text files anddisplay their contents directly on the browser, all without messing upthings too much with complex server-side programs. Moreover, AJAX comeswith native support for pulling out data served as XML, by using the“responseXML” property that belongs to the XMLHtttpRequest object.
Consideringthat XML is today one of the most common data carriers used whenworking with Web services, this second part of the series will putstrong attention to developing a JavaScript application that fetchesdata from an XML file, by taking advantage of the native capabilitiesthat AJAX brings to developers for working with this markup language.In my attempt to illustrate the relevant role of AJAX within the areaof remote scripting, by the end of this article you will know thebasics for using client-side parsed XML in your own applications.
Nowthat you know the objectives of this second part of the series, it’stime to move on to learn more about JavaScript-based XML processing.Let’s get going!
JavaScript Remote Scripting:Processing XML Files - XML in the client: the basics of AJAX XML processing
(Page 2 of 6 )
Inaddition to the “responseText” property that you saw in the firstarticle, the XMLHttpRequest object offers the “responseXML” property,useful for processingserverresponse, which has been sent back to the client as XML data. Usingregular DOM methods, it’s possible to parse basically XML in the clientand implement some kind of interaction, either for boosting thecapabilities of user interfaces or the application layer itself.
Withreference to the above deployed concepts, in conjunction with thesample news rotator that I developed in part one of this series, whatI’ll do next is write a simple script that retrieves some headlinesfrom a XML file, then processes them and finally displays the resultsdirectly on the browser. Considering that client-side flat text fileprocessing has already been covered, the next example will illustratehow to parse XML files once the corresponding http request has beensuccessfully completed.
As you might guess, in order toget the script parsing XML, first I’ll need to work with sample dataserved as XML. In this particular case, I’ll define a simple XML file,which contains some headlines to be included in the news rotator. Itsdefinition is the following:



Learn advanced concepts about AJAX and Remote Scripting. Visit DevArticles.com now!
http://www.devarticles.com


PHP 5.1 now presents new key improvements such as PDO (PHP Data Objects)
http://www.php.net


Google to continue extending its GoogleMaps API
http://www.google.com/apis/maps/documentation/


MySQL releases Open Source Database Tools for MacintoshOS X
http://www.mysql.com


Release of Flash Player 8 allows to develop richer applications and communications
http://www.macromedia.com


PHP introduces more improvements in regards to SOAP, streams and SPL
http://www.php.net


Asyou can see, the above listed XML file presents a simple structure fordefining the appropriate headlines to be displayed, as well as the URLstied to them. With reference to the document hierarchy, I’ve defined ageneral tag, which is placed on top of the document tree,and then created a few nodes to wrap up both and <url> child elements. Of course neither styledata nor element attributes have been defined for the document, thusits structure is very simple and understandable.<br>Now thatyou have a pretty clear idea of how the sample XML file looks, I canmove on to start writing the complete JavaScript application.<br>JavaScript Remote Scripting:Processing XML Files - Reading XML files with AJAX: defining the “sendRequest()” function<br>(Page 3 of 6 )<br>Ifyou’ve read the first part of this series, the “sendRequest()” functionshould be already pretty familiar. Essentially, it performs twowell-delimited tasks: the first one consists of instantiatingcross-browser XMLHttpRequest objects, while the second one isresponsible for sending the proper http request and fetching thecontents of the file passed as a function argument. Here is itsdefinition:<br>function sendRequest(doc){<br>// check for existing requests<br>if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4){<br>xmlobj.abort();<br>}<br>try{<br>// instantiate object for Mozilla, Nestcape, etc.<br>xmlobj=new XMLHttpRequest();<br>}<br>catch(e){<br>try{<br>// instantiate object for Internet Explorer<br>xmlobj=new ActiveXObject(‘Microsoft.XMLHTTP‘);<br>}<br>catch(e){<br>// Ajax is not supported by the browser<br>xmlobj=null;<br>return false;<br>}<br>}<br>// assign state handler<br>xmlobj.onreadystatechange=stateChecker;<br>// open socket connection<br>xmlobj.open(‘GET‘,doc,true);<br>// send GET request<br>xmlobj.send(null);<br>}<br>Insimple terms, the above defined function is flexible enough to handlemultiple data formats, so it’s not only restricted to reading XMLfiles. Notice that the “doc” argument could be any file feasible forbeing processed through a GET request, a feature that turns thefunction into a very versatile piece of code.<br>Also, bystudying the snippet a little bit deeper, it becomes clear that itallows for the fetching of content that is dynamically generated.Instead of passing in only the name of the file to be fetched, it’spossible to append some variables to the querystring, because it’s donewith regular links. For instance, if the requested file is“script_file.php”, it’s extremely easy to add a few parameters forprocessing on theserver,in the form “script_file.php?param1=1¶m2=2”. I guess this isenough of an explanation for you to start tweaking the code to pull outdynamic content.<br>Having explained how the “sendRequest()”function does its business, it’s time to take a look at the nextfunction “stateChecker()”, which as you’ll see in a moment, controlsthe flow of the whole program.<br>JavaScript Remote Scripting:Processing XML Files - Checking the progress of a request: a quick look at the “stateChecker()” function<br>(Page 4 of 6 )<br>Ifyou’re used to writing JavaScript functions that verify the status ofhttp requests, then the “statusChecker()” function should be prettystraightforward. First off, let’s see how it looks and then discuss itslogic:<br>function stateChecker(){<br>// if request is completed<br>if(xmlobj.readyState==4){<br>// if status == 200 display text file<br>if(xmlobj.status==200){<br>// create data container<br>createDataContainer();<br>// read XML data<br>data=xmlobj.responseXML.getElementsByTagName(‘message‘);<br>// display XML data<br>displayData();<br>}<br>else{<br>alert(‘Failed to get response :‘+ xmlobj.statusText);<br>}<br>}<br>}<br>Withreference to the function above, its logic can be explained through twosimple steps. Of course, the first one involves checking the request’sstatus by verifying the values of both “readyState” and “status”properties. Once the request has been successfully completed, thesecond step takes place. Notice that the code calls the“createDataContainer()” function, which is tasked with building therequired (X)HTML structure for displaying headlines. However, let’spause for a moment and pay attention to the following line:<br>data=xmlobj.responseXML.getElementsByTagName(‘message‘);<br>Whatthis line of code does is simply store in the “data” array all the“<message>” nodes defined within the XML file that you sawpreviously, by applying the “getElementsByTagName()” method to the“responseXML” property. In a nutshell, this expression shows how easyit is to fetch XML data, by utilizing only DOM methods.<br>Asyou can see, the rest of the functions are fairly straightforward.After reading and storing all the “<message>” nodes in an arraystructure, the only thing left to be done is display the appropriateheadlines. As you’ll see shortly, this operation is performed by the“displayData()” function.<br>JavaScript Remote Scripting:Processing XML Files - Displaying XML data: defining the “createDataContainer()” and “displayData()” functions<br>(Page 5 of 6 )<br>Inorder to display XML data fetched from a file, I’ll use a couple offunctions aimed at dealing with visual output. The first relevantfunction, “createDataContainer()” builds up a containing <div>element, which will be used to house all the headlines. Since thefunction only uses some common DOM methods, it shouldn’t be difficultto understand at all. Below is its corresponding definition:<br>function createDataContainer(){<br>var div=document.getElementById(‘container‘);<br>if(div){return};<br>var div=document.createElement(‘div‘);<br>div.setAttribute(‘id‘,‘container‘);<br>document.getElementsByTagName(‘body‘)[0].appendChild(div);<br>}<br>AsI said previously, the above snippet creates a <div> element,then assigns to it an ID attribute and finally appends it to thedocument tree. By leaving out the boring details, the only pointworth noting is the following checking line:<br>if(div){return};<br>SinceI don’t want to have multiple data containers on the same document eachtime this function is invoked, I avoid this condition simply bychecking for an existing containing element. In case I have such astructure, program flow is returned to calling code, without appendingany element.<br>Having explained how an XML data container iscreated through the DOM, the next step consists of defining a functionthat builds the required (X)HTML markup for displaying XML data. Thisis precisely the task of the “displayData()” function, which looks likethis:<br>function displayData(){<br>// reset data container<br>document.getElementById(‘container‘).innerHTML=‘‘;<br>var ul=document.createElement(‘ul‘);<br>for(var i=0;i<data.length;i++){<br>// create links<br>var li=document.createElement(‘li‘);<br>var a=document.createElement(‘a‘);<br>// assign ‘href‘ attribute<br>a.setAttribute(‘href‘,data[i].getElementsByTagName(‘url‘)<br>[0].firstChild.nodeValue);<br>// add link labels<br>a.appendChild(document.createTextNode(data<br>[i].getElementsByTagName(‘title‘)[0].firstChild.nodeValue));<br>li.appendChild(a);<br>ul.appendChild(li);<br>}<br>document.getElementById(‘container‘).appendChild(ul);<br>}<br>Asyou can see, the above function creates dynamically the requiredstructure for displaying the headlines. Regarding this particular case,I’ve decided to show the headlines as a set of regular links, wrappedup into an unordered (X)HTML list.<br>In addition to usingregular DOM methods, such as “createElement()” and “createTextNode()”for dynamic element generation, there is a couple of specific lines ofcode that deserve special attention. Notice the following statements:<br>a.setAttribute(‘href‘,data[i].getElementsByTagName(‘url‘)<br>[0].firstChild.nodeValue);<br>a.appendChild(document.createTextNode(data<br>[i].getElementsByTagName(‘title‘)[0].firstChild.nodeValue));<br>Usedwithin a loop, the first line is responsible for adding the“<url>" nodes to the “href” attribute of each link, while thesecond one builds the labels for each <a> tag. As a result, alist of links displaying headlines is created on the fly, by parsingthe XML <message> collection defined originally within the XMLdocument.<br>After running the script, the corresponding output, spiced up with some CSS styles, is depicted below:<br><img style='max-width:300px;' id="img0" src="http://image.360doc.cn/DownloadImg/14389/265247_1.gif" /><br>Atthis point, the complete set of functions has been discussed andexplained, thus the script is now capable of requesting a given XMLfile and displaying its contents, after applying some styling. Ofcourse, if you want to get a higher level of abstraction formanipulating XML files, this is easy to achieve by using more genericDOM constructs to navigate the document tree, such as the “childNodes”collection. This brings up an important point, since the way you buildthe XML document can affect the tree structure, causing the script tobreak down if you don’t adjust its code to handle a new tree.<br>Thereis still one additional improvement, easily applicable to the“displayData()” function. For displaying headlines at a given timeinterval through an automated mechanism, a JavaScript timer helps getthe job done, thus the rewritten function might be defined as follows:<br>function displayData(){<br>// reset data container<br>document.getElementById(‘container‘).innerHTML=‘‘;<br>var ul=document.createElement(‘ul‘);<br>for(var i=0;i<data.length;i++){<br>// create links<br>var li=document.createElement(‘li‘);<br>var a=document.createElement(‘a‘);<br>// assign ‘href‘ attribute<br>a.setAttribute(‘href‘,data[i].getElementsByTagName(‘url‘)<br>[0].firstChild.nodeValue);<br>// add link labels<br>a.appendChild(document.createTextNode(data<br>[i].getElementsByTagName(‘title‘)[0].firstChild.nodeValue));<br>li.appendChild(a);<br>ul.appendChild(li);<br>}<br>document.getElementById(‘container‘).appendChild(ul);<br>// update headlines each 1 hour<br>setTimeout("sendRequest(‘news.xml‘)",3600*1000);<br>}<br>Assumingthat headlines are stored in the “news.xml” file, the modified versionof the function now will request that file each hour, therefore bysetting up the appropriate http headers to tell the browser not tocache the document, any changes introduced within the XML file will beautomatically reflected by the output of the script.<br>Nowthat you have a clear idea about how to use AJAX for parsing XML files,it’s time to list the full source code for the script, so it’savailable to you in one place. In this way, you can use it for your ownconvenience.<br>JavaScript Remote Scripting:Processing XML Files - Putting the pieces together: listing the complete script<br>(Page 6 of 6 )<br>AsI said before, below is the list of the whole script, including a fewadditional lines to run the program after the page has been loaded:<br><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"<br>"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br><html><br><head><br><title>READING XML FILES WITH AJAX






To wrap up
That’sit for now. Throughout this second part of the series, you’ve hopefullylearned how to use AJAX for reading and manipulating simple XML files,in order to implement a basic Web service. Certainly, the concepts thatI illustrated at the very beginning imply a challenge for developingricher applications that use remote scripting to provide users with amore interactive experience.
The third tutorial of theseries goes one step further with remote scripting, by explaining itsimplementation through the use of fully-standard DOM methods, withoutgetting a single foot into AJAX technology. Want to know more? Justwait for the next part!
DISCLAIMER: The content provided in this article is not warrantied or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation best practices. We are not liable for any negative consequences that may result by implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.