如何在表中呈现 JSON 数据。我尝试使用以下代码:
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"}
]
最佳答案
当使用表和 AJAX 时,我会推荐 jQuery Datatables 插件。它为您完成了很多工作,并且如果您使用像 Laravel 这样的框架,那么还有大量的软件包
关于php - JSON jQuery 显示到表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24896753/