在解析字符串中访问XML节点

时间:2016-04-07 01:18:27

标签: javascript php html ajax xml

我通过PHP代理执行Ajax调用(来解决跨源"问题"),从不同域中的服务器接收XML。我没有从XML节点获取值到我的html标记中。我的浏览器控制台没有错误。在Firebug中,我可以在Response和XML列中看到XML数据。完整代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<h2>Flightinfo</h2>

<button type="button" onclick="loadXMLDoc()">
Get Flight ID</button>

<p id="fid"></p>

<script>
function loadXMLDoc() {
jQuery(document).ready(function($) { 
  $.ajax({
    url: "http://d2f.no/flightinfo/proxy.php",
    type: "POST",
    data: {
        address: "http://flydata.avinor.no/XmlFeed.asp?TimeFrom=1&TimeTo=7&airport=OSL&direction=D&lastUpdate=2016-03-10T15:03:00Z"
    },

    success: function myFunction(xml) {

  var x, i, xmlDoc, txt, parser;
  parser = new DOMParser(); // new Parser
  xmlDoc = parser.parseFromString(xmlDoc,"text/xml"); // Parse string
  txt = "";
  x = xmlDoc.getElementsByTagName("flight_id");
  for (i = 0; i< x.length; i++) {
  txt += x[i].childNodes[0].nodeValue + "<br>";
  }

   document.getElementById("fid").innerHTML = txt;

}

  }); 
});  
}
</script>
</body>
</html>

收到的部分XML数据:

    <airport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://flydata.avinor.no/XmlFeed.xsd" name="OSL">
<flights lastUpdate="2016-04-07T00:37:16Z">
<flight uniqueID="5760860">
<airline>OSL</airline>
<flight_id>OSL424</flight_id>
<dom_int>D</dom_int>
<schedule_time>2016-03-10T10:15:00Z</schedule_time>
<arr_dep>D</arr_dep>
<airport>BDU</airport>
<gate>PAD</gate>
</flight>
<flight uniqueID="5758058">
<airline>AC</airline>
<flight_id>AC6377</flight_id>
<dom_int>S</dom_int>
<schedule_time>2016-03-11T05:30:00Z</schedule_time>
<arr_dep>D</arr_dep>
<airport>BRU</airport>
<check_in>10</check_in>
</flight>

Link to XML feed

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

这是一种简化的方法,更多的是jQuery方式:

<button type="button" id="load_btn">Get Flight IDs</button>

<p id="fid"></p>

<script>
$( document ).ready(function() {
    $('#load_btn').click(function() {
        loadXMLDoc();
    });
});  

function loadXMLDoc() {

    $.ajax({
        url: "http://d2f.no/flightinfo/proxy.php",
        type: "POST",
        dataType: "xml",
        data: {
            address: "http://flydata.avinor.no/XmlFeed.asp?TimeFrom=1&TimeTo=7&airport=OSL&direction=D&lastUpdate=2016-03-10T15:03:00Z"
        },

    })

    .done(function (xml) {

        var ids = $(xml).find('flight_id');

        var txt = "";
        $.each(ids, function(index) {
            txt += ids[index].textContent + "<br>";
        }); 
        $('#fid').html(txt);
    });
}
</script>

代码中的一个问题是:

  xmlDoc = parser.parseFromString(xmlDoc,"text/xml"); // Parse string

两次使用xmlDoc。我相信你的意思是:

  xmlDoc = parser.parseFromString(xml,"text/xml"); // Parse string

此外,从jQuery 1.8开始,success has been deprecated赞成.done。