[英]Nested JSON to HTML table
我的代码中可能有一个愚蠢的错误,但是我还没有找到答案。 我正在使用来自http://rata.digitraffic.fi/api/v1/live-trains/[trainnumber]的 JSON数据,这是一个外部站点。
我的目标是从JSON数组中的数组中获取数据到一个简单的HTML表,在这种情况下,是所有timeTableRows -arrays中的stationShortCode,type,commercialTrack和ScheduledTime。 JSON数据如下所示:
[{"trainNumber":9707,
"departureDate":"2015-06-03",
"operatorUICCode":10,
"operatorShortCode":"vr",
"trainType":"HL",
"trainCategory":"Commuter",
"commuterLineID":"H",
"runningCurrently":false,
"cancelled":false,
"version":4295000475,
"timeTableRows":[
{
"stationShortCode":"HKI",
"stationUICCode":1,
"countryCode":"FI",
"type":"DEPARTURE",
"trainStopping":true,
"commercialStop":true,
"commercialTrack":"6",
"cancelled":false,
"scheduledTime":"2015-06-03T14:48:00.000Z"
},
{
"stationShortCode":"PSL",
"stationUICCode":10,
"countryCode":"FI",
"type":"ARRIVAL",
"trainStopping":true,
"commercialStop":true,
"commercialTrack":"3",
"cancelled":false,
"scheduledTime":"2015-06-03T14:52:30.000Z"
}, and 5 to 50 timeTableRows more.
从$ _GET获取火车号的json.php看起来像这样
<?php
$juna = $_GET["juna"];?>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<h1><?php
$juna = $_GET["juna"];
echo $juna;?></h1>
<script>
$.ajax({
url: 'http://rata.digitraffic.fi/api/v1/live-trains/<?php echo $juna;?>',
dataType: 'json',
success: function(data) {
$(row).appendTo('table.data');
row = '';
for (var i in data.timeTableRows) {
row += '<tr id="' + i + '">';
row += '<td>' + data.timeTableRows[i].stationShortCode + '</td>';
row += '<td>' + data.timeTableRows[i].commercialTrack + '</td>';
row += '<td>' + data.timeTableRows[i].scheduledTime + '</td>';
row += '<td>' + data.timeTableRows[i].type + '</td>';
row += '</tr>';
}
$(row).appendTo('table.data');
},
});
</script><table id="data"></table>
</body>
</html>
我确定确实存在一些愚蠢的错误,但是我自己看不到它们。
问题是您试图将具有一类data
的表追加到表中,但是您没有一个。 您的表的ID为data
,更改$(row).appendTo('table.data');
到$(row).appendTo('table#data');
因此,我再次从头开始编写了整个脚本,稍有改动。 JSON解析脚本现已发布
function myFunction(response) {
var obj = JSON.parse(response);
var i;
var out = "<table><tr><td>Juna</td><td>Asema</td><td>Pysähtyy</td><td>Aikataulu</td><td>Raide</td></tr>";
for(j = 0; j < obj.length; j++) {
for(i = 0; i < obj[j].timeTableRows.length; i++) {
out += "<tr><td>" +
obj[j].trainNumber +
"</td><td>" +
obj[j].timeTableRows[i].stationShortCode +
"</td><td>" +
obj[j].timeTableRows[i].commercialStop +
"</td><td>" +
obj[j].timeTableRows[i].scheduledTime +
"</td></tr>";
}
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
我还添加了第一个trainNumber列用于测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.