げぼげぼメモ

自分用いろいろメモです

File APIを使って読み込んだJsonをdatatablesで表示

Ajax通信を使う場合はブラウザの設定が必要だったりで大変なので
File APIで読み込めるようにします。

基本的なコードや使用しているデータはAjax通信でやったときのものです。
これだとファイルを読み込んでからdatatablesを初期化しているので、ファイルを読み込むまでテーブルの表示がおかしいです。
直し方はまた今度調べます。

<!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>
	<input type="file" name="file" id="file" accept="text/json">

    <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() {
		var elems = { "fileField": document.getElementById("file") };
		var reader = new FileReader();
		
		elems.fileField.addEventListener("change", function(e) {	
			reader.readAsText(e.target.files[0]);
		});

		reader.onload = function(e) {
			var jsonObj = JSON.parse(e.target.result);
			console.log(jsonObj);
			$('#testTable').DataTable({
				data: jsonObj.data,
				columns: [
				  { data: "name" },
				  { data: "position" },
				  { data: "salary" },
				  { data: "start_date" },
				  { data: "office" },
				  { data: "extn" }
				]
			})
		}
	});
</script>

</html>