DataTable填充Ajax

时间:2017-11-11 19:31:12

标签: json ajax

我有一个数据表js,我用ajax(json)填写,在我的json中,它的返回是几个条目,我通过控制台看到了这一点,但是,数据表只填充了第一个json记录。

我的代码

  $(document).ready(function()
    {
        $.ajax({
            type : 'POST',
            url  : 'view/list/clients_1.php',
            dataType: 'json',
            cache: false,
            success :  function(result)
            {
                //pass data to datatable

                console.log(result); // just to see I'm getting the correct data.
                $('#my_table').DataTable({
                    "searching": false, //this is disabled because I have a custom search.
                    "bAutoWidth": false,
                    "bFilter": true,
                    "bLengthChange": false,
                    "responsive": true,
                    "aaData": [result], //here we get the array data from the ajax call.
                    "aoColumns": [
                        { "sTitle": "#" },
                        { "sTitle": "Name" },
                        { "sTitle": "Work" }
                     ]
                });
            }
        });

文件代码:clients_1.php

    $clients_sql = 
    "
        SELECT
            *
        FROM
            client
    ";

    $result = mysqli_query($mysqli, $clients_sql);
    $dataArray = array();
    while( $row = mysqli_fetch_array($result) )
    {
        $dataArray[] = $row["client_id"];
        $dataArray[] = $row["client_name"];
        $dataArray[] = $row["client_work"];
    }
    echo json_encode($dataArray);

1 个答案:

答案 0 :(得分:1)

解决

            var table = $('#my_table').dataTable({

                serverSide: true,
                searching: false,
                bAutoWidth:false,
                bFilter: true,
                bLengthChange: false,
                responsive: true,
                ajax: "view/lista/clientes_1.php",
                dataSrc: 'data',
                columns: [
                    {sTitle: "#", data: 'client_id' },
                    {sTitle: "Name", data: 'client_nome' },
                    {sTitle: "Work", data: 'client_work' }
                ]
            }); // End: DataTable

            $('#search-table').unbind();
            $('#search-table').bind('keyup', function(e) {
                //if(e.keyCode == 13) {
                    table.fnFilter(this.value);
               // }
            });

PHP

    $result = mysqli_query($mysqli, $clients_sql);
    while($row = $result->fetch_array(MYSQLI_ASSOC))
    {
      $data[] = $row;
    }

    $results = [
        "sEcho" => 1,
        "iTotalRecords" => count($data),
        "iTotalDisplayRecords" => count($data),
        "aaData" => $data

    ];

    echo json_encode($results);
相关问题