jQuery實現頁面數據導出成.json文件

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script type="text/javascript" src="libs/jquery-1.11.2.js"></script>
	<script type="text/javascript" src="libs/jquery.tabletojson.js"></script>
</head>
<body>
	<table id="answered">
		<thead>
			<tr>
				<td>姓名</td>
				<td>年齡</td>
				<td>班級</td>
			</tr>
		</thead>
		<tbody>
		    <tr>
		      <td>lili</td>
		      <td>18</td>
		      <td>2班</td>
		    </tr>
		</tbody>
	</table>
	<button>導出json數據</button>

	<script type="text/javascript">
		$('button').click( function() {
			//把表格轉化成json數據
			var table = $('table').tableToJSON(); // Convert the table into a javascript object
			alert(JSON.stringify(table));
			console.log(table);
			console.log(JSON.stringify(table));

		  	// 下載文件方法
			var funDownload = function(content, filename) {
				var eleLink = document.createElement('a');
				eleLink.download = filename;
				eleLink.style.display = 'none';
				// 字符內容轉變成blob地址
				var blob = new Blob([content]);
				eleLink.href = URL.createObjectURL(blob);
				// 觸發點擊
				document.body.appendChild(eleLink);
				eleLink.click();
				// 然後移除
				document.body.removeChild(eleLink);
			};
			
			if('download' in document.createElement('a')) {
				funDownload(JSON.stringify(table), 'testInfo.json');
			} else {
				alert('瀏覽器不支持');
			}

		});
	</script>
</body>
</html>

這裏用到jQuery的開源插件Table-to-json:

官方地址:http://lightswitch05.github.io/table-to-json/

功能說明:將js對象table轉換成javascript對象,輸出json數據字符串。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章