<table>表數(shù)據(jù)轉(zhuǎn) Json 格式的javascript函數(shù)如下
代碼如下:
<script>
var keysArr = new Array("key0", "key1","key2");
function TableToJson(tableid) { //tableid是你要轉(zhuǎn)化的表的表名,是一個字符串,如"example"
var rows = document.getElementById(tableid).rows.length; //獲得行數(shù)(包括thead)
var colums = document.getElementById(tableid).rows[0].cells.length; //獲得列數(shù)
var json = "[";
var tdValue;
for (var i = 1; i < rows; i++) { //每行
json += "{";
for (var j = 0; j < colums; j++) {
tdName = keysArr[j]; //Json數(shù)據(jù)的鍵
json += "\""; //加上一個雙引號
json += tdName;
json += "\"";
json += ":";
tdValue = document.getElementById(tableid).rows[i].cells[j].innerHTML;//Json數(shù)據(jù)的值
if (j === 1) {//第1列是日期格式,需要按照json要求做如下添加
tdValue = "\/Date(" + tdValue + ")\/";
}
json += "\"";
json += tdValue;
json += "\"";
json += ",";
}
json = json.substring(0, json.length - 1);
json += "}";
json += ",";
}
json = json.substring(0, json.length - 1);
json += "]";
return json;
}
</script>
更多信息請查看IT技術專欄