Find and display XML data by attribute with AJAX

nodicloales

New Member
I have an XML document from which I am trying to fetch data to display on a webpage, and I want to show additional data from each XML entry on the same page, when a user clicks a specific item in the list. My page has a list of all items from my XML document, with the data attribute "data-id", and I want to fetch data from the XML document based on that same id.So for example, here is my html:\[code\]<ul> <li data-id="1">Apples</li> <li data-id="2">Oranges</li> <li data-id="3">Lemons</li> <li data-id="4">Grapes</li></ul>\[/code\]and here is my XML tree:\[code\]<food> <item id="1"> <name>Apples</name> <color>Green</color> </item> <item id="2"> <name>Oranges</name> <color>Orange</color> </item> <item id="3"> <name>Lemons</name> <color>Yellow</color> </item> <item id="4"> <name>Grapes</name> <color>Purple</color> </item></food>\[/code\]Is it possible, with AJAX, to display the colors of each item on my webpage using the setup I have described? Simply put, when a user clicks on apples, is possible to show an alert with the word "Green"?Here is my current code:\[code\]$(document).ready(function(){ $.ajax({ type: "GET", url: "/xml.aspx", dataType: "xml", success: parseXml });}); function parseXml(xml){ $(xml).find("item").each(function(){ $("ul").append("<li data-id='" + $(this).attr("id") + "'>" + $(this).find("name").text() + "</li>"); }); $("li").click(function(){ var item = $(this).attr("data-id"); $.ajax({ type: "GET", url: "/xml.aspx", dataType: "xml", success: function(xml){ $(xml).find(item).each(function(){ alert( $(this).find("color").text() ); }); } }); }); }\[/code\]
 
Top