【问题标题】:iterating xml with jquery用jquery迭代xml
【发布时间】:2015-02-13 23:07:49
【问题描述】:

我从 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>

【问题讨论】:

标签: jquery xml object iterate


【解决方案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);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="your-container"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-23
    • 2011-05-28
    • 1970-01-01
    • 2010-12-14
    • 2012-10-17
    • 2011-06-01
    • 1970-01-01
    相关资源
    最近更新 更多