JSON jQuery显示到表


JSON jQuery display to table

如何在表中呈现JSON数据。我尝试用下面的代码:

:

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

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"}
    ]

当使用表格和AJAX时,我建议使用jQuery Datatables插件。它为你做了很多工作,如果你使用像Laravel这样的框架,它有很多包。http://www.datatables.net

不要使用item[1]使用item[id],这是json,不只是一个数组,你甚至可以使用item.id.

将json data视为对象(这里是对象数组),该对象具有带有名称的属性,而不是数字(除非您将其设置为名称^^)

应该是

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

因为你有一个对象数组,你必须使用index访问元素,然后你访问它的属性