嵌套JSON到HTML表



我的代码中可能有一个愚蠢的错误,但我还没有找到答案。我正在使用来自http://rata.digitraffic.fi/api/v1/live-trains/[trainnumber]的JSON数据,这是一个外部站点。

我的目标是从JSON数组中的数组到一个简单的HTML表,在这种情况下,stationShortCode, type, commercialTrack和scheduletime从所有timeablerows -数组中获取数据。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.

json.php从$_GET获取车号,如下所示

    <?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列用于测试。

相关内容

  • 没有找到相关文章

最新更新