2014-07-22 69 views
0

如何呈現表中的JSON數據。我試着用下面的代碼:JSON jQuery顯示到表

HTML

<table> 
    <thead> 
    <tr> 
     <th>id</th> 

     <th>Name</th> 

     <th>Password</th> 
    </tr> 
    </thead> 
    <tbody id="tbody"></tbody> 
</table> 

<button id="get">Get</button> 

<script src="script/ajax.googleapis.com_ajax_libs_jquery_1.10.1_jquery.min.js" type="text/javascript"></script> 
<!--<script src="script/myScript.js" type="text/javascript"></script>--> 
<script src="script/json_array.js" type="text/javascript"></script>  

腳本的jQuery的

$(document).ready(function() { 
done(); 

}); 


function done() { 
     setTimeout(function() { 
     updates(); 
     done(); 
     }, 200); 
} 

function updates() { 
    $.getJSON("fetch.php", function(data) { 
     $.each(data, function (index, item) { 
    var eachrow = "<tr>" 
       + "<td>" + item[1] + "</td>" 
       + "<td>" + item[2] + "</td>" 
       + "<td>" + item[3] + "</td>" 
       + "<td>" + item[4] + "</td>" 
       + "</tr>"; 
    $('#tbody').append(eachrow); 
}); 
}); 
} 

PHP腳本

<?php 
include "./pdoConn.php"; 
$output = array(); 
$query = "select * from wishers"; 
$stmt = $pdo->query($query); 
$stmt->execute(); 
$name = $stmt->fetchAll(PDO::FETCH_ASSOC); 
echo json_encode($name); 
?> 

輸出JSON的:

[ 
     {"id":"1","name":"Tom","password":"098f6bcd4621d373cade4e832627b4f6"}, 
     {"id":"2","name":"Jerry","password":"098f6bcd4621d373cade4e832627b4f6"}, 
     {"id":"3","name":"Kate","password":"098f6bcd4621d373cade4e832627b4f6"}, 
     {"id":"4","name":"Joan","password":"098f6bcd4621d373cade4e832627b4f6"}, 
     {"id":"5","name":"Cyril","password":"098f6bcd4621d373cade4e832627b4f6"}, 
     {"id":"8","name":"Ama","password":"ama"},  
     {"id":"7","name":"Akusika","password":"mummy"}, 
     {"id":"9","name":"Abetiafa","password":"joko"} 
    ] 
+0

您可以嘗試:https://json2html.herokuapp.com/ 我開發了這個應用程序(開源)。 JSON 2 HTML解析器是用Python編寫的。嘗試一下,代碼在https://github.com/softvar/json2html-flask – softvar

回答

0

當表和AJAX的工作,我會建議jQuery的數據表插件。它做了很多關於你的工作,有很多的包,如果你使用像Laravel框架

http://www.datatables.net

0

不要使用項目[1]使用項目[ID],這是JSON ,不僅僅是一個數組,你甚至可以使用item.id.

見JSON DATAS爲對象(這裏的對象數組),這個對象有屬性有一個名字,不是數字(除非你將其設置爲名稱^^)

+0

item ['id'],對不起;) –

+0

謝謝你正在工作 –

0

應該

var eachrow = "<tr>" 
      + "<td>" + item[index].id + "</td>" 
      + "<td>" + item[index].name + "</td>" 
      + "<td>" + item[index].password + "</td>" 
      + "</tr>"; 

由於您有一個對象數組,因此您必須使用index訪問該元素,然後才能訪問其屬性。