views:

151

answers:

3

Using an ajax POST request in jQuery, I get the following xml back from the server:

<?xml version="1.0"?>
<data>

  <subject>
    <val1>...</val1>
    <val2>...</val2>
    <val3>...</val3>
  </subject>

  <subject>
    <val1>...</val1>
    <val2>...</val2>
    <val3>...</val3>
  </subject>

  ... 

</data>

The xml will have an arbitrary number of <subject> tags. How do I loop through each of the subject tags, grabbing the data in val1..val3 for the corresponding tag in each iteration? Thanks.

+1  A: 

Using DOM methods:

var subjects = xml.getElementsByTagName("subject");
for(i in subjects){
  alert(subjects[i].getElementByTagName("val1").textContent;
  alert(subjects[i].getElementByTagName("val2").textContent;
  alert(subjects[i].getElementByTagName("val3").textContent;
}
Marius
+2  A: 

Make sure your server response sends a "Content-Type" header of "text/xml". Then the response will be the parsed xml document. Your success handler has only to then iterate the resulting DOM:

$.post(url, postData, function(xmlDoc) {
    $('subject', xmlDoc).each(function() {
     var val1 = $('val1', this).text();
     var val2 = $('val2', this).text();
     var val3 = $('val3', this).text();
    })
});
Crescent Fresh
I tried this and it worked for the val# that happened to have varchar data from the database. But the val tag that had text type data (mySql) showed up blank when I tried to pop up $('val#', this).text(); Any ideas why this would be?
es11
@es111: I'd have to see the xml. Post an update.
Crescent Fresh
nevermind, I was being dumb, for one of the val# tags I was actually using <body></body> which I guess is why it didn't pick up the value..simply changing it to a different name worked..thank you
es11
A: 

I can't find the syntax right now, but you can query the object using selectors just like you do html, something like:

$.get('your/url', function(response) {
  $(response).contents("subject"); // just like it's HTML
});
Chris Missal