如何在表中呈现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> 脚本-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"}
]发布于 2014-07-22 20:12:41
在使用表和AJAX时,我建议使用jQuery Datatables插件。它为您做了很多工作,如果您使用像Laravel这样的框架,那么就会有大量的包。
http://www.datatables.net
发布于 2014-07-22 20:21:56
不要使用item1使用itemid,这是json,不仅仅是一个数组,您甚至可以使用item.id。
请参阅json数据作为对象(这里是一个对象数组),该对象具有带有名称的属性,而不是数字(除非将其设置为名称^^)。
发布于 2014-07-22 22:12:58
它应该是
var eachrow = "<tr>"
+ "<td>" + item[index].id + "</td>"
+ "<td>" + item[index].name + "</td>"
+ "<td>" + item[index].password + "</td>"
+ "</tr>";因为您有一个对象数组,所以必须使用index访问元素,然后访问它的属性。
https://stackoverflow.com/questions/24896753
复制相似问题