2

我试图将数据库表数据解析为动态变化的 jquery 数据表。json_encode在php的函数之后我得到了以下输出

$sql = "SELECT * FROM login";

$result = mysql_query($sql);
$a= array();
while ($row = mysql_fetch_assoc($result)) {
$a[][] = $row;
    }

    echo (json_encode($a));

json输出

[[{"id":"1","username":"test11","password":"$2y$10$NiKnEN\/ww8yGVhv3JNjSuO5FfOFSthadS2B3GcbA3KGBktAOSu6lK","role":"Administrator "}],[{"id":"2","username":"test","password":"test","role":"test"}]]

然后我按照他们所说的调用jquery数据表ajax函数。这是我的编码

 $('#example').dataTable( {
        "ajax": 'ab.php'
    } );

tbody但最终在 jquery 数据表部分仅显示“正在加载...”文本。这是为什么?

4

2 回答 2

4

If you using datatable 1.10 api, you need to create a json response like :

$json_data = array(
    "draw"            => intval( $_REQUEST['draw'] ),
    "recordsTotal"    => intval( $totaldata ),
    "recordsFiltered" => intval( $totalfiltered ),
    "data"            => $data
);
echo json_encode($json_data);
  • draw: we send same number which has been send by datatable at time of draw/request.

  • recordsTotal: Total numbers of records in your table.

  • recordsFiltered: Total numbers of filtered records after searching in your table. If you do not perform any search then recordsFiltered will be same as recordsTotal.

  • data: Your fetched records data. You have to fetched the data as per start, length, search value, colomn name and sorting orders parameters. you can download dummy database table from here

Please refer this link to know the details

于 2015-03-17T13:02:25.557 回答
4

原因

显然您使用的是 DataTables 1.10 版。默认情况下,此版本要求数据采用某种格式,有关详细信息,请参阅DataTables 文档

{
    "data": [
        // row 1 data source,
        // row 2 data source,
        // etc
    ]
}

解决方案

在您的 PHP 中更改$a[][] = $row;$a['data'][] = $row以正确格式生成数据。

于 2015-03-16T11:51:49.843 回答