【问题标题】:Parse XML objects to HTML ul element将 XML 对象解析为 HTML ul 元素
【发布时间】:2017-09-02 18:19:42
【问题描述】:

这是来自网络服务的响应 XML:

<information>
    <customer>
        <customer_id>asdf1_id</customer_id>
        <customer_name>asdf1</customer_name>
    </customer>
    <customer>
        <customer_id>asdf2_id</customer_id>
        <customer_name>asdf2</customer_name>
    </customer>
    <customer>
        <customer_id>asdf3_id</customer_id>
        <customer_name>asdf3</customer_name>
    </customer>
</information>

而且,我需要获取每个客户,并将其解析为 HTML &lt;ul&gt;

因此,基本上,Web 服务会返回带有 1、2、3、4 或任何数量的客户的 XML,我需要 AJAX 解析此信息 到&lt;ul&gt; html 元素,应该是这样的:

<li onclick='UpdateCustomer(asdf1_id)'>asdf1</li>
<li onclick='UpdateCustomer(asdf2_id)'>asdf2</li>
<li onclick='UpdateCustomer(asdf3_id)'>asdf3</li>

那么,我需要什么 AJAX 代码来解析对 &lt;ul&gt; 内的 &lt;li&gt; 对象的 XML 响应?

【问题讨论】:

    标签: javascript jquery html ajax xml


    【解决方案1】:

    试试这个:

    jQuery:

    $(document).ready(function() {
        $.ajax({
            type: "GET",
            url: "information.xml",
            dataType: "xml",
            success: function(response) {
                $('customer', response).each(function() {
                    $(".ulcontainer").append($("<li onclick=UpdateCustomer(" + $(this).find("customer_id").text().trim() + ")>" + $(this).find("customer_name").text() + "</li>"));
                });
            }
        });
    });
    

    HTML:

    <ul class="ulcontainer">
    
    </ul>
    

    基本上将您的 XML 放入文件 information.xml 并使用 GET 请求来获取您的数据。成功获取数据后,使用 jQuery each 函数循环遍历您的每个 customer 标签并获取其中的信息。

    编辑:我修改了我的 AJAX 调用,为您提供上述所需的 &lt;li&gt; 标记。

    【讨论】:

      猜你喜欢
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多