我从jquery ajax请求获得xml响应,我想提取每个项目的名称和价格。我坚持处理这个问题的最佳方法。从读数来看,似乎将XML作为javascript对象渲染是最好的选择,但我无法找到语法来完成此任务并迭代...
$.ajax({
type: "POST",
url: "myPgm.php",
success: function(xml) {
var xmlDoc = $.parseXML(xml);
// now I want to iterate through the xml payload
// ....
}
})
xml看起来像这样:
<items>
<item>
<name>item1</name>
<price>888</price>
</item>
<item>
<name>item2</name>
<price>999</price>
</item>
<items>
答案 0 :(得分:1)
parseXML实际上很容易。这是一个非常简单的例子:
$(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);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="your-container"></div>
&#13;