datatables不会用ajax和mysql加载

kgsdhlau  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(328)

不知何故,我从这段代码中得到了一个无效的json响应。我们的目标是在表中显示sql数据,所有功能都是搜索和排序https://datatables.net/. 问题出在哪里?
获取.php

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$query ="SELECT * FROM users"; 
$result = $mysqli->query($query);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
      $results = ["sEcho" => 1,
          "iTotalRecords" => count($row),
          "iTotalDisplayRecords" => count($row),
          "aaData" => $row ];
        echo json_encode($results, JSON_PRETTY_PRINT);
    }
} else {
    echo "empty table";
}

$mysqli->close();

get.php响应

{
    "sEcho": 1,
    "iTotalRecords": 2,
    "iTotalDisplayRecords": 2,
    "aaData": {
        "id": "26",
        "name": "test",
        "pass": "2"
    }
}

js公司

$(document).ready(function() {
  $('#my-example').dataTable({
    "bProcessing": true,
    "sAjaxSource": "get.php",
    "aoColumns": [{ 
        mData: 'name'
      }, {
        mData: 'pass'
    }]
  });
});

html格式

<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<table id="my-example">
  <thead>
    <tr>
      <th>name</th>
      <th>pass</th>
    </tr>
  </thead>
</table>
kqhtkvqz

kqhtkvqz1#

您的php代码返回的数组应该是这样的,它有义务 data 作为你返回的数据 error 作为最终的错误:

{
  "data": [
    [
      "Text going into the first column",
      "second column",
      "third column"
    ]
  ]
}

所以在你的例子中,你的数组看起来是这样的:

[
  "data": [
    [
      "1",
      count($data),
      count($data),
      $data
    ]
  ]
]

在循环中,还需要使用 $row['column'] .
测试用例

相关问题