Handling XML Data for Ajax - Populating the Form on a Microsoft Browser
(Page 4 of 5 )
The msPopulate() function is reproduced in Example 4-6.
Example 4-6. The msPopulate( ) function
1 function msPopulate() {
2 var resp = req.responseText;
3
4 var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
5 xmlDoc.async="false";
6 xmlDoc.loadXML(resp);
7
8 dec = xmlDoc.getElementsByTagName('decimal');
9 var decimal = document.getElementById('decimal');
10 decimal.value=dec[0].firstChild.data;
11
12 hexi = xmlDoc.getElementsByTagName('hexadecimal');
13 var hexadecimal = document.getElementById('hexadecimal');
14 hexadecimal.value=hexi[0].firstChild.data;
15
16 oct = xmlDoc.getElementsByTagName('octal');
17 var octal = document.getElementById('octal');
18 octal.value=oct[0].firstChild.data;
19
20 bin = xmlDoc.getElementsByTagName('binary');
21 var binary = document.getElementById('bin');
22 binary.value=bin[0].firstChild.data;
23
24 hypertextml = xmlDoc.getElementsByTagName('hyper');
25 var hyper = document.getElementById('hyper');
26 hyper.value=hypertextml[0].firstChild.data;
27 }
Here, we use the built-in browser functions that Ihave touted as a programmer power play. We start by getting theActiveXObject calledMicrosoft.XMLDOM(line 4). Next, we load the response from the servlet into the XML document (line 6).
Now we can mine the document for the data. First we get the data between the<decimal></decimal>tags. To do this, we first retrieve the XML data field information, by callinggetElementsByTagName(elementName)(line 8); this function returns the array of child nodes belonging to the element (parent node) associated with the given tag. After we get the array of child nodes, we can reference the first element in the child node by callingfirstChild. We then obtain the value of the child node by referencing thedatafield. So, to sum it up, we get our decimal value fromdec[0].firstChild.data.
If you are parsing a document that contains multiple tags with the same tag name, you can access any of the values by indexing the array. For example, if you had another<decimal>value</decimal>entry, you would index it with this call:
dec[1].firstChild.data.
After obtaining the decimal value from the XML, line 10 updates thedecimalform element. We've now retrieved one value from the XML and displayed it on the page. We continue on in this fashion until all of our data fields are updated with the values retrieved from the XML DOM sent from the servlet.
Next: Populating the Form on Other Browsers >>
More XML Tutorials Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the book Ajax on Java, written by Steven Douglas Olson (O'Reilly, 2007; ISBN: 0596101872). Check it out today at your favorite bookstore. Buy this book now.
|
|