2015-10-13 33 views
-1

我試圖在HTML表格中顯示JSON數據,但我不知道如何。我試圖使用jQuery。如何根據使用jquery的動態數據在html表格上顯示JSON數據?

我的數據是這樣的:

{ 
    "error": "", 
    "response_code": 200, 
    "position": "Train Arrived at Barauni Jn. (BJU) at 05:45 PM", 
    "train_number": "12554", 
    "total": 21, 
    "route": [ 
     { 
      "status": "No Delay", 
      "actdep": "07:50 PM", 
      "station": "New Delhi (NDLS)", 
      "actarr": "12:00 AM", 
      "no": 1, 
      "scharr": "Source", 
      "schdep": "07:50 PM" 
     }, { 
      "status": "4 Minutes Before", 
      "actdep": "08:28 PM", 
      "station": "Ghaziabad (GZB)", 
      "actarr": "08:26 PM", 
      "no": 2, 
      "scharr": "08:30 PM", 
      "schdep": "08:32 PM" 
     }, 
     //... 
     { 
      "status": "30 Minutes Late", 
      "actdep": "N/A", 
      "station": "Barauni Jn (BJU)", 
      "actarr": "05:45 PM", 
      "no": 21, 
      "scharr": "05:15 PM", 
      "schdep": "Destination" 
     } 
    ] 
} 
+0

你應該先格式化你的問題,然後發佈你嘗試過什麼等等遠? –

回答

0

你可以試試這個代碼。添加了一些筆記,讓你瞭解它正在做什麼。我假定你正試圖循環收集路線。

HTML:

<table id="routes" class="table"> 
    <thead></thead> 
    <tbody></tbody> 
</table> 

的jQuery:

function dataToTable($table, obj, collectionName) { 

    //Load the properties as headings. 
    $thead = $table.find('thead'); 
    $tr = $('<tr />'); 
    //get property names and add a th for each property 
    for (property in obj[collectionName][0]) { 
     $th = $('<th />'); 
     $th.html(property); 
     $tr.append($th); 
    } 
    //append header row to thead 
    $thead.append($tr); 

    //load the data from the routes to the tbody. 
    $tbody = $table.find('tbody'); 

    $.each(obj[collectionName], function() { 
     //create row per record 
     $tr = $('<tr />'); 
     //dynamically get values by property name and load to a td 
     for (property in this) { 
      $td = $('<td />'); 
      $td.html(this[property]); 
      $tr.append($td); 
     } 
     //append row to tbody 
     $tbody.append($tr); 
    }); 

} 

//function run example 
dataToTable($('#routes'),data,'route') 

DEMO:

http://jsfiddle.net/SeanWessell/6ozt7n66/

+0

我認爲我無法將您的代碼添加到我的身邊,因爲下面的過程不起作用... –

+0

嘗試傳遞data.d而不是數據,例如... dataToTable($('#routes'),data.d ,'route')如果不起作用,請添加一行console.log(data)並使用控制檯的結果編輯您的問題。 –

相關問題