げぼげぼメモ

自分用いろいろメモです

Datatables Ajax通信 Jsonファイルオブジェクト読み込み

datatableのデータとしてオブジェクト形式のjsonデータを使うやり方。
ローカルで表示する場合はchromeだとセキュリティポリシーがうんたらでファイルが読み込めないので、firefoxを使うかオプション付きでchromeを起動しておく必要がある。

test.html

<!DOCTYPE html>
<html lang="ja">
  <head>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/s/dt/dt-1.10.10/datatables.min.css"/>
      <script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
      <script type="text/javascript" src="https://cdn.datatables.net/s/dt/dt-1.10.10/datatables.min.js"></script>
  </head>
<body>
    <table id="testTable" class="table table-bordered">
        <thead>
            <tr>
                <th>name</th>
                <th>position</th>
                <th>salary</th>
                <th>start_date</th>
                <th>office</th>
                <th>extn</th>
            </tr>
        </thead>
    </table>
</body>

<script>
    $(document).ready(function() {
      $('#testTable').DataTable({
        "ajax": {
          url: "data.json",
        },
        columns: [
          { data: "name" },
          { data: "position" },
          { data: "salary" },
          { data: "start_date" },
          { data: "office" },
          { data: "extn" }
        ]
      });
    });
</script>

</html>

data.json

{
  "data": [
    {
      "name":       "Tiger Nixon",
      "position":   "System Architect",
      "salary":     "$3,120",
      "start_date": "2011/04/25",
      "office":     "Edinburgh",
      "extn":       "5421"
    },
    {
      "name":       "Garrett Winters",
      "position":   "Director",
      "salary":     "$5,300",
      "start_date": "2011/07/25",
      "office":     "Edinburgh",
      "extn":       "8422"
    },
    {
      "name":       "Tiger Nixon",
      "position":   "System Architect",
      "salary":     "$3,120",
      "start_date": "2011/04/25",
      "office":     "Edinburgh",
      "extn":       "5421"
    }
  ]
}