XMLHttpRequest API显示在更新的表中

时间:2018-10-02 13:48:52

标签: javascript html json xml api

我正在尝试创建一个表格,该表格显示到达港口的船舶的预计到达时间。我正在调用API:

https://services.marinetraffic.com/api/expectedarrivals/v:3/apikey/portid:DKKAL/protocol:xml/timespan:1

这给了我想要显示在HTML表格中的响应,该响应会在据说有新船到达港口时更新:

<ETA>
 <VESSEL_ETA MMSI="21840000" ETA="2018-10-03T08:00:00"/>
</ETA>

到目前为止,这是我所拥有的:

<button type="button" onclick="loadDoc()">SHIPS</button>
<table id="ships"></table>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
  }
 };

  xhttp.open("GET","https://services.marinetraffic.com/api/expectedarrivals/v:3/apikey/portid:DKKAL/protocol:xml/timespan:1", true);
  xhttp.send();
 }
 function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>MMSI</th><th>ETA</th></tr>";
  var x = xmlDoc.getElementsByTagName("ETA");
  for (i = 0; i <x.length; i++) {
    table += "<tr><td>" +
    x[i].getElementsByTagName("MMSI")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("ETA")[0].childNodes[0].nodeValue +
    "</td></tr>";
  }
  document.getElementById("ships").innerHTML = table;
}
</script>

但是,除了表头之外,什么都没有显示。如何使它显示xml响应,并在将新船添加到列表时更新它?

1 个答案:

答案 0 :(得分:1)

您对XML的处理不正确

您要查找的节点是VESSEL_ETA,而不是ETA

和MSSI / ETA是这些节点的属性,而不是子节点

如此

<button type="button" onclick="loadDoc()">SHIPS</button>
<table id="ships"></table>

<script>
    // this is a dummied up loadDoc - which has no errors in the question
    // this calls myFunction with a dummied up XMLHttpRequest response
    function loadDoc() {
        let rawxml = `<ETA>
 <VESSEL_ETA MMSI="21840000" ETA="2018-10-03T08:00:00"/>
</ETA>`;
        var xmlDoc = new DOMParser().parseFromString(rawxml, 'text/xml');
        myFunction({responseXML: xmlDoc});
    }
    
    function myFunction(xml) {
        var i;
        var xmlDoc = xml.responseXML;
        var table="<tr><th>MMSI</th><th>ETA</th></tr>";
        var x = xmlDoc.getElementsByTagName("VESSEL_ETA");
        for (i = 0; i <x.length; i++) {
            table += '<tr><td>' + 
                x[i].getAttribute('MMSI') + 
                '</td><td>' + 
                x[i].getAttribute('ETA') + 
                '</td></tr>';
        }
        document.getElementById("ships").innerHTML = table;
    }
</script>