如何使用json数据和ajax创建动态jquery数据表?

时间:2016-10-10 06:32:43

标签: javascript jquery json ajax datatable

我试图用jquery和json创建一个动态数据表。我试图确定键并将它们设置为标题,然后将键中的值设置为表中的行。

到目前为止,我的代码是:

<script type="text/javascript">
$('#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);
      },
      type: 'GET'
   });
});
</script>

但我一直收到错误消息:

(index):80 Uncaught TypeError: Cannot set property 'innerHTML' of null

My JSON data structure

JSfiddle

如何根据返回的json数据创建动态数据表,设置从表头到表中值的所有内容?

5 个答案:

答案 0 :(得分:4)

我在你的代码中做了两处修改,似乎在那之后工作了。

1)在div'info'之后添加了一个id为'showData'的div。

<div id="showData">
</div>

2)附上$('#action-button')。点击($(document)中的function().ready(function()。

$(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);
            },
            type: 'GET'
        });

    });

}); 

错误说它期望一个id为'showData'的div。

答案 1 :(得分:0)

首先,对于数据表,您需要创建静态标题部分。我在这里分享我最简单的代码。

<div class="table-responsive" style="margin-top:20px;">
    <table id="tblPatientDiagnosed" class="table table-vcenter table-responsive table-condensed table-bordered display">
        <thead>
            <tr>
                <th class="text-center" width="20%">Consultant Id</th>
                <th class="text-center" width="30%">Consultant Name</th>
                <th class="text-center" width="30%">Patinet Name</th>
                <th class="text-center" width="20%">No. of time seen</th>
            </tr>
        </thead>            
    </table>
</div>

这是我的数据表静态负责人。

现在在文档就绪功能中,您需要初始化它。

var tblPatientDiagnosed = '';
$(document).ready(function() {

  tblPatientDiagnosed = $('#tblPatientDiagnosed').DataTable({
    "bPaginate": true,
    aaSorting:[],
    "processing": true,
    "sPaginationType": "full_numbers",
  });

  $("#action-button").on('click',function(){

  tblPatientDiagnosed.fnClearTable();//fisrtly clearing data-table data if exist

  $.ajax({
    type: "POST",
    cache: false,
    url: "controllers/admin/add_treatment.php",
    datatype:"json",
    data: postData,

    success: function(data) {            
        var parseData = JSON.parse(result);
        var datalength = parseData.length;
        for(var i=0; i < datalength; i++){
            var staffId = parseData[i].consultant_id;
            var staffLength = staffId.length;
            for (var j=0;j<6-staffLength;j++) {
                staffId = "0"+staffId;
            }
            staffId = staffPrefix+staffId;
            tblPatientDiagnosed.fnAddData([staffId,'data1','data2','data3']);//write the varibale or data you got from ajax
        }
    }
  }); 
});

fnadddata添加行

答案 2 :(得分:0)

你可以帮我Foo table plugin来解决你的问题,这对我来说很好。并且有许多排序过滤内置功能,您可以使用它们。

答案 3 :(得分:0)

<html>
<head>
<script>

    function createdynamictable(yourdata)
    {

        //the parameter must be a json data

        var parsedata = JSON.parse(yourdata)        
        var table = document.createElement("table");

        for (var i = 0; i <= parsedata.length; i++)
        {
            tr = table.insertRow(-1);

            for (var key in parsedata[0])
            {
                if (i == 0)
                {
                   //Inserting columns fields to the table
                    var trCell = tr.insertCell(-1);
                    trCell.innerHTML = key;
                }
                else
                {
                    //Inserting table values to the table
                    var trCell = tr.insertCell(-1);
                    trCell.innerHTML = parsedata[i-1][key];
                }

            };

        }


        var div = document.getElementById("showtable");
        div.innerHTML = "";
        div.appendChild(table);

    }
</script>

</head>


<body>


<div id="showtable"></div>


</body>

</html>

答案 4 :(得分:0)

如何通过ajax JSON响应生成包含动态列标题和数据的表。

//Javascript code

    $.ajax({
        "url": SitePath + "/Attendance/getEmployeeMonthYearlyReport",
        "data": {
            MonthYear: $("#txtEmpMonth").val()
        },
        "type": "GET",
        "dataType": "JSON"
    }).success(function (response) {
        var objData1 = JSON.parse(response);
        var myList = objData1.outdata.Table[0];
        var tableHeaders = '';
        var tableBody = '';
        $.each(myList, function (k, v) {
            tableHeaders += "<th>" + k + "</th>";
            tableBody += "<td>" + v + "</td>";
        });
        $("#tblid").append('<thead><tr>' + tableHeaders + '</tr></thead>');
        $("#tblid").append('<tbody><tr>' + tableBody + '</tr></tbody>');
    })
    
@* Html code *@

<table class="table-striped table-bordered" id="tblid"  align="center" width="100%"></table>