Javascript 使用来自 GET 请求的 JSON 数组填充数据表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33362593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:59:01  来源:igfitidea点击:

Populating Datatables with JSON array from GET request

javascriptjqueryjsondatatables-1.10

提问by Smajl

I know that there has been many answers and tutorials about populating Jquery Datatableswith data but I always get to the point of getting the following exception:

我知道有很多关于用数据填充 Jquery数据表的答案和教程,但我总是得到以下异常:

Uncaught TypeError: Cannot read property 'length' of undefined

未捕获的类型错误:无法读取未定义的属性“长度”

I, being mainly a backend developer, have little to no experience with writing client so I would like to ask you about what I am doing wrong in the following example.

我,主要是后端开发人员,几乎没有编写客户端的经验,所以我想问你我在下面的例子中做错了什么。

I have a server running locally exposing an endpoint /destinationwhich responds with a JSON string in this format:

我有一个在本地运行的服务器公开一个端点/destination,该端点以以下格式响应 JSON 字符串:

[{
    "id": 1,
    "name": "London Heathrow",
    "lat": 51.470022,
    "lon": -0.454295
}, {
    "id": 2,
    "name": "London Gatwick",
    "lat": 51.153662,
    "lon": -0.182063
}, {
    "id": 3,
    "name": "Brussels Airport",
    "lat": 50.900999,
    "lon": 4.485574
}, {
    "id": 4,
    "name": "Moscow Vnukovo",
    "lat": 55.601099,
    "lon": 37.266456
}]

I would like to display these data in a table using the Datatables plugin. This is the table code:

我想使用 Datatables 插件在表格中显示这些数据。这是表代码:

<table id="example" class="display" cellspacing="0" width="100%">
     <thead>
         <tr>
             <th>ID</th>
             <th>Name</th>
             <th>Lattitude</th>
             <th>Longitude</th>
         </tr>
        </thead>
 </table>

And script to populate it:

和脚本来填充它:

$(document).ready(function() {
    $('#example').DataTable({
        "processing" : true,
        "ajax" : {
            "url" : ".../destination",
            "type" : "GET"
        },
        "columns" : [ {
            "data" : "id"
        }, {
            "data" : "name"
        }, {
            "data" : "lat"
        }, {
            "data" : "lon"
        }]
    });
});

As specified above, I am getting the Uncaught TypeError: Cannot read property 'length' of undefined. Any help is appreciated.

如上所述,我正在获取Uncaught TypeError: Cannot read property 'length' of undefined. 任何帮助表示赞赏。

EDIT: It works if I do a request for the data and then pass the data to the datatables as follows:

编辑:如果我请求数据然后将数据传递给数据表,它会起作用,如下所示:

$.ajax({
            url : '/AOS-project/destination',
            type : 'GET',
            dataType : 'json',
            success : function(data) {
                assignToEventsColumns(data);
            }
        });

        function assignToEventsColumns(data) {
            var table = $('#example').dataTable({
                "bAutoWidth" : false,
                "aaData" : data,
                "columns" : [ {
                    "data" : "id"
                }, {
                    "data" : "name"
                }, {
                    "data" : "lat"
                }, {
                    "data" : "lon"
                } ]
            })
        }

I was expecting the datatables to have this functionality baked in...

我期待数据表具有此功能......

回答by davidkonrad

Set dataSrcto ''. As the documentationstates :

设置dataSrc''。正如文档所述:

Get JSON data from a file via Ajax, using dataSrc to read data from a plain arrayrather than an array in an object:

通过 Ajax 从文件中获取 JSON 数据,使用 dataSrc从普通数组而不是对象中的数组读取数据

$(document).ready(function() {
    $('#example').DataTable({
        "processing" : true,
        "ajax" : {
            "url" : "https://api.myjson.com/bins/14t4g",
            dataSrc : ''
        },
        "columns" : [ {
            "data" : "id"
        }, {
            "data" : "name"
        }, {
            "data" : "lat"
        }, {
            "data" : "lon"
        }]
    });
});

and your code works -> http://jsfiddle.net/nzn5m6vL/

并且您的代码有效-> http://jsfiddle.net/nzn5m6vL/

回答by Shailendra Sharma

If you code working with hard json than try it

如果您使用硬 json 进行编码,请尝试

$(document).ready(function() {
    $('#example').DataTable({
        processing : true,
        ajax: {
                url: "/api/venues",
                "type" : "GET"
                dataSrc: function (json) {
                    var obj = JSON.parse(json);
                    console.log(obj);
                    return obj;
                 }
            },
        columns : [ {
            data : "id"
        }, {
            data : "name"
        }, {
            data : "lat"
        }, {
            data : "lon"
        }]
    });
});