如何使用Jquery或Javascript将HTML表格数据作为json数据下载到.txt文件中。
问题描述:
如何使用Jquery或JavaScript将HTML表格数据作为json数据下载到.txt文件中。
How to download HTML table data as json data in to .txt file using Jquery or JavaScript.
答
让我们将您的任务分解为2个单独的任务,例如as-
1。将HTML表格转换为JSON数据
Let's break your task in to 2 separate tasks, such as-
1. Convert HTML table to JSON data
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=1; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
参考: http://stackoverflow.com/ a / 6271924/1006297 [ ^ ]
2。将JSON数据写入文件
Reference: http://stackoverflow.com/a/6271924/1006297[^]
2. Write JSON data to file
var url = 'data:text/json;charset=utf8,' + encodeURIComponent(data);
window.open(url, '_blank');
window.focus();
参考:http://stackoverflow.com/a/22055706/1006297 [ ^ ]
希望,有帮助:)
Reference: http://stackoverflow.com/a/22055706/1006297[^]
Hope, it helps :)