从ajax json填充数据表 [英] Populate Datatable from ajax json

查看:166
本文介绍了从ajax json填充数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表格没有填充.我可以看到它正在获取正确的JSON

My table is not populating. I can see that it is getting the correct JSON

收到的JSON数据如下:

JSON Data received looks like this:

[
  {
    "id": "1",
    "name": "FooBar",
    "predicted": "0",
    "points": "1",
    "section_id": "1",
    "detail_alias": ""
    ...
  },
  ...
]

HTML

<table id="example"></table>

JS

$('#example').dataTable( {
    "ajaxSource": "rest/index.php?m=foo",
    "columns": [
        { "data": "id" },
        { "data": "name" },
        { "data": "detail_alias" },
        { "data": "points" }
    ]
} );

我在浏览器中看到的是:

All I'm seeing in my browser is:

当网络"标签显示呼叫具有正确数据的响应为200时,它会显示正在加载...".

It says "Loading..." when the network tab shows that the call had a 200 response with the correct data.

为什么表格没有填充?

推荐答案

所以我问题中的ajaxSource希望数据格式化为这样的格式:

So the ajaxSource in my question was expecting data to be formatted as such:

{ data: [ { ...

我也不想修改后端以这种格式发送数据,因为这会在其他地方引起问题.我假设最终在此页面上寻找解决方案的其他人可能也会遇到相同的问题.

And I didn't want to have to modify my back end to send data in this format as it would cause problems in other places. I'm assuming other people that end up on this page looking for a solution will likely have the same issue.

我的解决方案是通过jQuery.ajax()获取数据,然后将其传递到aaData字段,如下所示:

My solution was to get the data via jQuery.ajax() and then pass it in to the aaData field, like this:

$.ajax({
    'url': "/rest/index.php?m=foo",
    'method': "GET",
    'contentType': 'application/json'
}).done( function(data) {
    $('#example').dataTable( {
        "aaData": data,
        "columns": [
            { "data": "id" },
            { "data": "name" },
            { "data": "detail_alias" },
            { "data": "points" }
        ]
    })
})

这使我不必担心更改问题格式中的json数据.

This allows me to not have to worry about changing the json data from the format in the question.

无论如何,我还是更喜欢这种方式,因为如果我想同时修改或使用其他任何数据,它将给我带来更大的灵活性.

I like this way better anyway as I feel it gives me more flexibility if I wanted to do modify or use the data for anything else at the same time.

这篇关于从ajax json填充数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆