如何将动态表转换为jquery数据表?

时间:2016-10-11 00:06:09

标签: javascript jquery json ajax datatable

我正在从json data动态创建HTML表格。然后我想将此表转换为数据表。但是,当我尝试这样做时,我不断收到一条错误: Uncaught TypeError: Cannot read property 'mData' of undefined

我的jquery是:

$(document).ready(function() {
    $('#action-button').click(function() {
                $.ajax({
                    url: 'https://api.myjson.com/bins/1oaye',
                    data: {
                        format: 'json'
                    },
                    error: function() {
                        $('#info').html('<p>An error has occurred</p>');
                    },
                    dataType: 'json',
                    success: function(data) {
                        // EXTRACT VALUE FOR HTML HEADER. 
                        var col = [];
                        for (var i = 0; i < data.length; i++) {
                            for (var key in data[i]) {
                                if (col.indexOf(key) === -1) {
                                    col.push(key);
                                }
                            }
                        }

                        // CREATE DYNAMIC TABLE.
                        var table = document.createElement("table");


                        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

                        var tr = table.insertRow(-1);                   // TABLE ROW.

                        for (var i = 0; i < col.length; i++) {
                            var th = document.createElement("th");      // TABLE HEADER.
                            th.innerHTML = col[i];
                            tr.appendChild(th);
                        }

                        // ADD JSON DATA TO THE TABLE AS ROWS.
                        for (var i = 0; i < data.length; i++) {

                            tr = table.insertRow(-1);

                            for (var j = 0; j < col.length; j++) {
                                var tabCell = tr.insertCell(-1);
                                tabCell.innerHTML = data[i][col[j]];
                            }
                        }

                        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
                        var divContainer = document.getElementById("showData");
                        divContainer.innerHTML = "";
                        divContainer.appendChild(table);

                        // convert it to a data table
                        table.setAttribute("id", "example");
                        $('#example').DataTable();

                    },
                    type: 'GET'
                });
            });
        });

如何从json创建动态表或将其转换为数据表?

JSFiddle showing the issue

1 个答案:

答案 0 :(得分:1)

只需快速查看DataTable代码,看起来可能的原因是您没有将<th>放在<thead>部分中。目前他们位于<tbody>

这里有更新的小提琴...... https://jsfiddle.net/8some9a0/1/