AJAX Javascript Help Requested
Posted: Thu Jun 08, 2006 11:33 pm
Hello,
I'm developing an AJAX application but I'm not big on Javascript. All the examples I have seen seem to be rather poorly coded. What I would like to make is an XML parser in Javascript to parse the response.
Here is an example.
What I would like to do with this is have the Javascript parse this and loop through all the tags inside the data tag. It would then update the corresponding div on the web page.
If the div tag doesn't exist, it should just skip it. I haven't found any code that can do this and I don't know how to write it. What I do have is below, but it only works for one field..
I think what I need is a modified version of this...
Can someone please help me?
I'm developing an AJAX application but I'm not big on Javascript. All the examples I have seen seem to be rather poorly coded. What I would like to make is an XML parser in Javascript to parse the response.
Here is an example.
Code: Select all
<?xml version="1.0">
<data>
<data1>Name</data1>
<data2>Fruit</data2>
<data3>Vegetable</data3>
<data4>Captain</data4>
</data>Code: Select all
<div id="data1"></div>
<div id="data2"></div>
<div id="data3"></div>
<div id="data4"></div>Code: Select all
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
var update = new Array();
if(response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById(update[0]).innerHTML = update[1];
}
}
}Code: Select all
/* Reference the product_list element to the variable product_list */
product_list = XMLReponse.getElementByTagName('product_id');
/* By substituting product_list for XMLResponse, we will be searching
only the product_list element, not the entire response
We also use getElementsByTagName, not getElementByTagName,
since we are interested in all of the results, not just one. */
product_id = XMLResponse.getElementsByTagName('product');
/* getElementsByTagName produces an array, which we can access like this:
product_id[n], the same way we access an array item in PHP.
Let's get the id attribute from the product elements like this: */
for(i=0; i<product_id.length; i++){ //length is the same as count($array)
id = product_id[i].getAttribute('id') //Grabs the id attribute.
/* To get the text from within a text node, we use firstChild.data
for the corresponding element. */
name = product_id[i].getElementByTagName('name').firstChild.data;
version = product_id[i].getElementByTagName('version').firstChild.data;
}