jquery .dataTables使用ajax数据源小示例

<script type="text/javascript" language="javascript" src="./plugins/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript" language="javascript" src="./plugins/jquery.dataTables/dataTables/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="./plugins/jquery.dataTables/dataTables/jquery.dataTables.min.css" />
<style>
  /* 表格表头和数据都水平居中,默认居左 */
  .table > tbody > tr > td {
    text-align: center;
  }

  .table > thead:first-child > tr:first-child > th {
    text-align: center;
  }
</style>
<div id="container" style="width: 50%">
  <table id="myTable" style="width: 100%; white-space: nowrap">
    <thead>
      <tr>
        <th>name</th>
        <th>age</th>
        <th>score</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
<script>
  $(function () {
    let i = 1;
    const table = $("#myTable")
      .on("preXhr.dt", function (e, settings, data) {
        console.log("begin request");
      })
      .DataTable({
        serverSide: false,
        //不检索
        searching: false,
        //不排序
        ordering: false,
        //不允許用戶更改表的分页显示长度
        lengthChange: false,
        ajax: {
          // url可以直接指定远程的json文件
          url: "../test1.php",
          type: "POST",
          // 传给服务器的数据,可以添加我们自己的查询参数
          data: function (param) {
            param.num = i++;
            return param;
          },
          //处理数据
          dataSrc: function (json) {
            for (var i = 0, length = json.data.length; i < length; i++) {
              json.data[i][1] = json.data[i][1] + "";
            }
            return json.data;
          },
          error: function () {
            console.log("error");
          },
        },
        //自定义列
        columnDefs: [
          {
            targets: [0],
            render: function (data, type, full) {
              return "<span style='color:red;'>" + data + "</span>";
            },
          },
        ],
        //本地化
        language: {
          lengthMenu: "每頁顯示_MENU_條記錄",
          zeroRecords: "沒有數據",
          info: "顯示第_PAGE_頁,共_PAGES_頁",
          infoEmpty: "沒有記錄",
        },
      });

    setInterval(() => {
      // 请求不同的url
      // table.ajax.url(url).load();
      // 请求同一个url
      table.ajax.reload(function (json) {}, true);
    }, 3000);
  });
</script>

 

<?php

$ex = [
    ['ee',  24,  34],
    ['tt',  23, 45]
];
$data = [];
if ($_POST['num']) {
    $num = $_POST['num'];
    for ($i = 0; $i <= $num; $i++) {
        foreach ($ex as $item) {
            $data[] = $item;
        }
    }
}

echo json_encode(['data' => $data, 'num' => $num]);

 

posted @ 2022-12-12 16:54  carol2014  阅读(337)  评论(0编辑  收藏  举报