gpt4 book ai didi

javascript - 更新表中的 XMLHttpRequest API 显示

转载 作者:行者123 更新时间:2023-11-30 20:08:47 25 4
gpt4 key购买 nike

我正在尝试创建一个表格来显示船舶到达港口的预计到达时间。我正在调用 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 响应,并在新船添加到列表时让它更新?

最佳答案

您对 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>

关于javascript - 更新表中的 XMLHttpRequest API 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52609736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com