加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何通过Ajax在jQuery DataTables中显示JSON数据?

发布时间:2020-12-16 02:48:52 所属栏目:百科 来源:网络整理
导读:我一直在尝试在jQuery DataTables组件中获取我的 JSON数据. 首先,我编写了一个JavaScript和一个类似下面代码的视图: $.fn.dataTable.Editor({ ajax: "http://localhost/example22/index.php?r=site/display",table: "#example",fields: [{ label: "Name:",n
我一直在尝试在jQuery DataTables组件中获取我的 JSON数据.

首先,我编写了一个JavaScript和一个类似下面代码的视图:

$.fn.dataTable.Editor({
    ajax: "http://localhost/example22/index.php?r=site/display",table: "#example",fields: [{
        label: "Name:",name: "name"
    },{
        label: "Designation:",name: "designation"
    },{
        label: "Address:",name: "address"
    },{
        label: "Salary:",name: "salary"
    }]
});

$('#example').DataTable({
    lengthChange: false,ajax: "http://localhost/example22/index.php?r=site/display",columns: [{
        allk: "name"
    },{
        allk: "designation"
    },{
        allk: "address"
    },{
        allk: "salary"
    }],select: true
});

和一个看法

<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Designation</th>
                <th>Address</th>
                <th>Salary</th>
            </tr>
        </thead>
</table>

并且提供的url分别包含以下JSON数据

{
    "allk": [
        {
            "name": "raju","designation": "developer","address": "he is from viswasapuram","salary": "30000"
        },{
            "name": "bob","designation": "designer","address": "no idea","salary": "100000"
        },{
            "name": "suresh","address": "fffswss","salary": "1212"
        },{
            "name": "john","address": "california","salary": "3000000"
        },"designation": "tester","address": "he is from cheeran maanagar","salary": "20000"
        }
    ]
}

有人可以帮我解决如何在这个应用程序中使用DataTables吗?

解决方法

使用ajax.dataSrc选项在JSON响应中指定属性保存数据.

例如:

$('#example').DataTable({
   // ... skipped other options ...
   ajax: {
       url: "http://localhost/example22/index.php?r=site/display",dataSrc: 'allk'
   },columns: [
       { data: "name"},{ data: "designation"},{ data: "address" },{ data: "salary"}
   ]
});

DEMO

有关代码和演示,请参见this jsFiddle.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读