使用AJAX从xml API检索数据

时间:2017-11-12 23:41:10

标签: ajax xml

我试图从api中检索数据,有人可以帮助我如何获取ajax中元素中某些子标记的节点值吗?我的XML api看起来像这样:

<distance ...>
<status>...</status>
<car>
<name>Golf</name>
<year>2016</year>
</car>
......
<car>
<name>BMW</name>
<year>2017</year>
</car>
</distance>

如何检索所有名称和年份标记值?下面是脚本,我在需要帮助的区域写了评论。感谢

<!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <script>
                function searchXML()
                {
                    var xmlhttp = new XMLHttpRequest();
                    var url = "https://www.example.se/api/products/xml";
                    xmlhttp.onreadystatechange = function () {
                        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                            console.log(xmlhttp.responseXML);
                            //Here I need help on how to retrieve data.
                            //when I used document.get....., I was getting .getElementsByClassName instead of getElementsById

                        }
                    };
                    xmlhttp.open("GET", url, true);
                    xmlhttp.send();
                }
            </script>
            <title></title>
        </head>
        <body>
            <h2>The returned data under this text</h2>
            <div id="mydata">
            </div>
            <button type="button" onclick="searchXML()">Get data</button>
        </body>
    </html>

1 个答案:

答案 0 :(得分:0)

您可以使用XML DOm操作API&#39; S var xmlDoc = xml.responseXML;

nodeValue 返回节点值

这是一个示例XML ..

<bookstore>

<book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

<book category="web">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>

<book category="web" cover="paperback">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

</bookstore>

正在为节点值解析为

(抱歉,CORS错误......代码段可以在Firefox上运行)

&#13;
&#13;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "https://www.w3schools.com/xml/books.xml", true);
xhttp.send();

function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName('title')[0];
    var y = x.childNodes[0];
    document.getElementById("demo").innerHTML =
    y.nodeValue;    // gets the node value
}
&#13;
<p id="demo"></p>
&#13;
&#13;
&#13;