Reputation: 377
In my code below I can loop through my xml file, but I can't find a way to output a random set on page load for example: (Banana 4011).
I'm not familiar with xml and getting its contents with javascript.
// my code outputs ( BananaLemon )
// plu.xml
<?xml version='1.0' ?>
<doc>
<item>
<name>lemon</name>
<code>4053</code>
</item>
<item>
<name>banana</name>
<code>4011</code>
</item>
</doc>
//javascript
$(document).ready(function(){
$.ajax({
type: "GET" ,
url: "plu.xml" ,
dataType: "xml" ,
success: function(xml) {
var xmlDoc = $.parseXML( xml );
//if single item
var plu = $(xml).find('item').text();
//but if it's multible items then loop
$(xml).find('name').each(function(){
$("#item").append($(this).text());
});
}
});
});
// Any knowledge is greatly appreciated, and thank you.
Upvotes: 0
Views: 49
Reputation: 42054
You don't need $parseXML and you can iterate directly on the parents: item:
$.ajax({
type: "GET" ,
url: "1.xml" ,
dataType: "xml" ,
success: function(xml) {
$(xml).find('item').each(function(){
$("#item").append($('<p/>', {text: 'name: ' + $(this).find('name').text() +
' code: ' + $(this).find('code').text()}));
});
}
});
From your comment:
Still curious how to return one random result set from the xml file
the code is:
$.ajax({
type: "GET" ,
url: "1.xml" ,
dataType: "xml" ,
success: function(xml) {
var eles = $(xml).find('item');
var rn = Math.floor(Math.random() * eles.length);
$("#item").append($('<p/>', {text: 'name: ' + eles.eq(rn).find('name').text() +
' code: ' + eles.eq(rn).find('code').text()}));
}
});
Upvotes: 1