DIV CSS 佈局教程網

如何把 Ajax 返回的 JSON 數據循環輸出成 Table
編輯:AJAX基礎知識     

本例演示如何把後端返回的 JSON 數據,用 jQuery 遍歷後動態渲染成表格行。

一、前端 Ajax 請求

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

二、後端返回 JSON(ThinkPHP)

$list = $File->group('num')->order('id desc')
        ->limit($Page->firstRow . ',' . $Page->listRows)->select();
$this->ajaxReturn($list, 'JSON');

三、HTML 表格結構

<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 到表格中,即可實現動態表格渲染。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved