表数据转 Json 格式的javascript函数如下
<script> <br />var keysArr = new Array("key0", "key1","key2"); <br />function TableToJson(tableid) { //tableid是你要转化的表的表名,是一个字符串,如"example" <br />var rows = document.getElementById(tableid).rows.length; //获得行数(包括thead) <br />var colums = document.getElementById(tableid).rows[0].cells.length; //获得列数 <br />var json = "["; <br />var tdValue; <br />for (var i = 1; i < rows; i++) { //每行 <br />json += "{"; <br />for (var j = 0; j < colums; j++) { <br />tdName = keysArr[j]; //Json数据的键 <br />json += "\""; //加上一个双引号 <br />json += tdName; <br />json += "\""; <br />json += ":"; <br />tdValue = document.getElementById(tableid).rows[i].cells[j].innerHTML;//Json数据的值 <br />if (j === 1) {//第1列是日期格式,需要按照json要求做如下添加 <br />tdValue = "\/Date(" + tdValue + ")\/"; <br />} <br />json += "\""; <br />json += tdValue; <br />json += "\""; <br />json += ","; <br />} <br />json = json.substring(0, json.length - 1); <br />json += "}"; <br />json += ","; <br />} <br />json = json.substring(0, json.length - 1); <br />json += "]"; <br />return json; <br />} <br /></script>