StealthRT StealthRT - 1 month ago 13
Ajax Question

AJAX / Jquery XML parse

I am trying to parse the following type of XML (data from getMembers.php):

<?xml version="1.0" encoding="ISO-8859-1"?>
<members>
<id>3422345</id>
<name>Bill Gates</name>
<id>232311</id>
<name>Bob Barker</name>
</members>


And i am using this code below to parse that:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "getMembers.php",
cache: false,
dataType: "xml",
success: function(xml) {
$(xml).find('members').each(function(){
var name = $(this).find("name").text()
alert(name);
});
}
});
});
</script>


No errors but i am getting both names at the same time..

Like:


Bill GatesBob Barker <--first loop>


Instead of


Bill Gates <--first loop>

Bob Barker <--second loop>


Any help would be great!

David

Answer

I think you iterate over members, not names:

success: function(xml) {
                $(xml).find('members').each(function(){
                    $(this).find("name").each(function(){
                        var name = $(this).text();
                        alert(name);
                    });
                });
            }

Or maybe your XML should looks like:

<members>
   <id>3422345</id>
   <name>Bill Gates</name>
</members>
<members>
   <id>232311</id>
   <name>Bob Barker</name>
</members>
Comments