2

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.

3 Answers 3

2

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();
    })
});
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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
1

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;
}

Comments

0

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.