本例演示如何把後端返回的 JSON 數據,用 jQuery 遍歷後動態渲染成表格行。
<script>
$(function(){
$('#test').click(function(){
$.ajax({
url: '__APP__/Article/jsonTest',
type: 'post',
success: function(data){
var item;
$.each(data, function(i, result){
item = "<tr><td>" + result['num'] + "</td><td>" + result['title']
+ "</td><td>" + result['credate'] + "</td><td>操作</td></tr>";
$('.table').append(item);
});
}
})
});
});
</script>
$list = $File->group('num')->order('id desc')
->limit($Page->firstRow . ',' . $Page->listRows)->select();
$this->ajaxReturn($list, 'JSON');
<table class="table table-striped table-bordered table-condensed"> <tr><th>編號</th><th>名稱</th><th>創建時間</th><th>操作</th></tr> </table>
核心要點:後端把數據以 JSON 返回,前端在 success 回調裡用 $.each 遍歷數組,把每一條記錄拼接成 <tr> 並 append 到表格中,即可實現動態表格渲染。