从ajax请求中读取xml响应

时间:2016-04-09 20:44:59

标签: jquery ajax xml

我想从以下来自ajax请求的xml代码中读取name和id 并转换为表格。我不知道如何解析xml或阅读它。有人可以帮助我吗?

<pre>
  <ConversionResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/invoicerRESTapi.Controllers">
    <Id>0</Id>
    <Result>0</Result>
    <lesson_details_list xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <d2p1:string>anik</d2p1:string>
    <d2p1:string>1</d2p1:string>
    <d2p1:string>manik</d2p1:string>
    <d2p1:string>2</d2p1:string>
    <d2p1:string>fnametest</d2p1:string>
    <d2p1:string>3</d2p1:string>
    <d2p1:string i:nil="true"/>
    <d2p1:string>4</d2p1:string>
    <d2p1:string>jamal</d2p1:string>
    <d2p1:string>5</d2p1:string>
    </lesson_details_list>
    <month i:nil="true"/>
    </ConversionResult>
</pre>

编辑1(客户代码)


    function displayCustomer() {

        $.ajax({

            url: "http://localhost:31517/customer",
            type: "GET",
            dataType: "xml",

        }.then(function (xml) {
            var doc = $(xml.documentElement);
            doc.find("lesson_details_list *").each(function (index, el) {
                console.log($.trim(el.textContent))
            })
        })

        );

    }

编辑2

basic.js

function displayCustomer(){

$.ajax({

    url: "http://localhost:31517/customer",
    type: "GET",
    dataType: "xml",

}.then(function (xml) {
    var doc = $(xml.documentElement);
    doc.find("lesson_details_list *").each(function (index, el) {
        console.log($.trim(el.textContent))
    })
})

);

}

的index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Client Api for consuming REST service</title>
    <script src="js/jquery-1.12.3.js"></script>
    <script src="js/basic.js"></script>
</head>
<body>
    <table id="customer_table">

    </table>

</body>
</html>
<script>
$(document).ready(function(){
    displayCustomer();
});
</script>

编辑3:

解决

工作代码

function displayCustomer() {

        $.ajax({
            url: "http://localhost:31517/customer",
            type: "GET",
            dataType: "xml"
        }).then(function (xml) {
            var doc = $(xml.documentElement);
            doc.find("lesson_details_list *").each(function (index, el) {
                console.log($.trim(el.textContent))
            })
        })

}

1 个答案:

答案 0 :(得分:0)

您可以将返回的documentElement的{​​{1}}定义为jQuery对象变量;使用选择器xml.find()链接到documentElement jQuery对象,以选择"lesson_details_list *"元素lesson_details_list的子节点来迭代.each()的子节点,{ {1}}在lesson_details_list

的子节点内返回文本
.textContent

jsfiddle https://jsfiddle.net/6gke3432/2/