PDA

View Full Version : grabbing xml with AJAX



kasei
11-06-2008, 09:54 AM
Hi,

I have an AJAX script that grabs some text from an xml file and posts it in a <div> on my webpage.

The xml file looks like this:


<?xml version="1.0" ?>
- <root>
- <message id="200830704.4951752">
<text>Buy my junk!</text>
</message>
</root>

And this is the function that get's the text:


function handleReceiveText() {
if (receiveReq.readyState == 4) {
var text_div = document.getElementById('div_text');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
var n_messages = message_nodes.length
for (i = 0; i < n_messages; i++) {
var text_node = message_nodes[i].getElementsByTagName("text");
text_div.innerHTML = '<div>' + text_node[0].firstChild.nodeValue + '</div>';
lastMessage = (message_nodes[i].getAttribute('id'));
}
mTimer = setTimeout('getText();',120000); //Refresh the text in 2 minutes
}
}

This works fine, but I'd like to have multiple items in multiple divs and I can't seem to figure out how to get it to work.

I thought it might work if I added these lines:


<?xml version="1.0" ?>
- <root>
- <message id="200830704.4951752">
<text>Buy my junk!</text>
</message>
- <image id="200830704.4951753">
<img>junk.jpg</img>
</image>
</root>


And this is the function that get's the text:


function handleReceiveText() {
if (receiveReq.readyState == 4) {
var text_div = document.getElementById('div_text');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
var n_messages = message_nodes.length
for (i = 0; i < n_messages; i++) {
var text_node = message_nodes[i].getElementsByTagName("text");
text_div.innerHTML = '<div>' + text_node[0].firstChild.nodeValue + '</div>';
lastMessage = (message_nodes[i].getAttribute('id'));
}
var img_div = document.getElementById('div_img');
var image_nodes = xmldoc.getElementsByTagName("image");
var n_images = image_nodes.length
for (i = 0; i < n_images; i++) {
var img_node = image_nodes[i].getElementsByTagName("img");
img_div.innerHTML = '<img src="' + img_node[0].firstChild.nodeValue + '">';
lastMessage = (message_nodes[i].getAttribute('id'));
}
mTimer = setTimeout('getText();',120000); //Refresh the text in 2 minutes
}
}

But it didn't work.

I'd like it to be able to grab 4 different types of information from the xml file and then place each information into 4 different <div>s

Can anyone tell me what I'm doing wrong?

Jesdisciple
11-06-2008, 07:12 PM
Please post a link to a page on your site which exhibits the problem. I think the page needs to be debugged and a live URL is the easiest way to accomplish that.

kasei
11-07-2008, 06:42 AM
Well!

I set up an example on my server, like you asked, and in doing so I got it to work!

I wonder what I did differently...

Anyway, thanks. :)

Joe