1

I get an xml response from a jquery ajax request and I want to extract name and price for each item. I am stuck on the best way to handle this. From readings, it seems that rendering XML as a javascript object is best bet, but I am having trouble finding syntax to accomplish this and iterate through ...

$.ajax({
    type: "POST",
    url: "myPgm.php",           
    success: function(xml) {    
        var xmlDoc = $.parseXML(xml);
        // now I want to iterate through the xml payload
        // ....
        }
    })

xml look like this:

<items>
   <item>
       <name>item1</name>
       <price>888</price>
       </item>
  <item>
       <name>item2</name>
       <price>999</price>
   </item>
<items>
itp
  • 43
  • 1
  • 5

1 Answers1

1

It's actually really easy with parseXML. Here's a super simple example:

$(function () {
    var xml = "<items><item><name>item1</name><price>888</price></item><item><name>item2</name><price>999</price></item></items>",
        // parse the XML
        xmlDoc = $.parseXML(xml),
        // convert it to a jQuery Object
        $xml = $(xmlDoc),
        // find out how many items there are to loop over
        itemCount = $xml.find("item").length,
        // create variables for name and price
        $name = $xml.find("name"),
        $price = $xml.find("price")
    ;
    // loop over the items, outputting the name and price for each one
    for ( i=0; i < itemCount; i++) {
         var html = '<li>Name: '+$($name[i]).text()+'<br/>Price: $'+$($price[i]).text()+'</li>';
      // append the items to a ul element
        $('#your-container').append(html);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="your-container"></div>
ReLeaf
  • 1,368
  • 1
  • 10
  • 17