<!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數據字符串。