Reputation: 2422
I'm having a simple php page the echo simple xml data like this
<user>
<username>jack</username>
<userage>20</userage>
</user>
<user>
<username>sally</username>
<userage>30</userage>
</user>
<user>
<username>steph</username>
<userage>40</userage>
</user>
and using this jquery code to display these information inside a div after clicking a button like this
$(document).ready(function(){
$("#get").on('click',function(){
$.get('dataxml.php',function(data){
var str = '';
$(data).find('user').each(function(){
var uname = ''; var uage = '';
$(this).find('username').each(function(){
uname = $(this).text();
});
$(this).find('userage').each(function(){
uage = $(this).text();
});
str += "<div><p class='uname'>"+uname+"</p><p class='uage'>"+uage+"</p></div>";
});
console.log(str);
$("#result").html(str);
});
});
});
console says 'empty string' but when i view the console data i get this as in the image and the #result div is empty. So what's the error and how can I fix it?
Upvotes: 2
Views: 440
Reputation: 193311
When you use
$(data).find('user')
it yields nothing because user
are a root nodes of your XML document (technically the structure is not valid XML).
You can instead go with
$(data).each(function() {
// ...
});
directly to iterate over username
nodes.
The best thing to do however is to wrap entire response with some node so the XML will become:
<users>
<user>
<username>jack</username>
<userage>20</userage>
</user>
<user>
<username>sally</username>
<userage>30</userage>
</user>
<user>
<username>steph</username>
<userage>40</userage>
</user>
</users>
Then you will be able to use $(data).find('user')
.
Upvotes: 2