Datatablesの使い方・ダウンロード方法は
http://qiita.com/nissuk/items/7ac59af5de427c0585c5
を参考にしてね。
・コントローラーでAJAXを吐く
SitesController.php
public function ajaxSearch()
{
// $query = $this->Sites->find()
// ->select(['id','name']):
//
// $customers = $this->paginate($query)->toArray();
$customers = [
0 => [
'id' => mt_rand(0,1000),
'name' => '太郎'
],
1 => [
'id' => 101,
'name' => '花子'
]
];
$this->set('customers', $customers);
$this->set('_serialize', ['customers']);
}
・適当なビュー
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script>
$(function () {
var url = "/sites/ajaxSearch/";//ここだけ変更すれば動く
// 日本語化
$.extend( $.fn.dataTable.defaults, {
language: {
url: "https://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Japanese.json"
}
});
table = $("#foo-table").DataTable({
//表示数切り替えを消す
lengthChange: false,
//初期表示数
pageLengh: 1000,
// 情報表示 無効
info: false,
// ページング機能 無効
paging: false,
//並び替えさせないのとセットで使う。でないと並び替えボタンが消えない。
// デフォルトソート
//order: [[ 1, "desc" ]],
//columnDefs: [
// {
// //並び替えさせない
// targets: [ 0 ],
// orderable: false
// },
// {
// className: "id",
// targets: [ 1 ]
// },
// {
// className: "memo", "targets": [ 4 ]//tdに名前をつける
// }
// ],
ajax: {
url: url,
dataSrc: function ( json ) {
//ここで形式などを変更することも可能。for文でリンクをつけたりとか。
return json.customers;//json形式がおかしいので、わざわざ指定しておく
}
},
columns: [
{ data: "id" },
{ data: "name" }
]
});
$(document).on('click', '.json-load', function() {
//他のURLを読み込む
//別のURLをロード
url = "/okws/writers/ajaxSearch/1/";
table.ajax.url(url).load();
// データをリロードする
table.ajax.reload();
});
});
</script>
<table id="foo-table" class="table table-bordered">
<thead>
<tr><th>ID</th><th>名前</th></tr>
</thead>
</table>
<button class="json-load">再読込</button>
javascript 内の var url だけ変更すれば、コピペで動く。
一番気をつけるべきは、jsonの形式。
一旦コールバック関数で変数を指定してやる。
応用
jquery ajax table で サーバー側にPOSTデータを渡す
ajax: {
url: url,
type:"POST",
data: function ( d ) {
//サーバー側 $_POST に [myKey] => myValue が渡される
d.myKey = "myValue";
},
dataSrc: function ( json ) {
//ここで形式などを変更することも可能。for文でリンクをつけたりとか。
return json.customers;//json形式がおかしいので、わざわざ指定しておく
}
},