• HTML Table to JSON 转


    I am updating a tool that allows users to customize a large data table to their needs. It's sort of like a progressive insurance for seminaries in that it helps students compare information on about 30 US seminaries so they can make an informed decision about where to go.

    My initial approach when I built it 4-5 years ago was to embed JSON data in the HTML page and then use JavaScript to convert that JSON data into a table based on the user's choices.

    But there are a few problems with this approach.

    1. The data is not accessible to screen readers.
    2. The data is not accessible to those without JavaScript
    3. Embedding a lot of JSON data in an HTML page isn't a very good idea. It should be a separate cached .js file, but I can't do that since the data often changes and it still wouldn't address #1 and #2

    So I've decided in the new version to start with a large <table> and then turn that table into JSON data using the <thead> region as the JSON labels. Then I can take that data and customize it based on the user's choices. Interestingly the overall data size is a bit smaller since writing a <td> and </td> for each peice of information is actually smaller than writing the header name and quotes over and over.

    Here's the simple table to JSON code. It assumes the first row is has header names and removes spaces and lower cases it.

    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;
    }
    

    Below are links to the two pages for comparison. Please note that the site where the "new" page is is still a work in progress and won't be launched for a month or two.

  • 相关阅读:
    VS2012 打包部署程序
    请求筛选模块被配置为拒绝包含 hiddenSegment 节的 URL 中的路径
    “远程服务器返回错误: (404) 未找到”的正确解决方法
    23.IDEA 运行junit单元测试方法
    Java单元测试之JUnit篇
    22.IntelliJ IDEA 切换 project
    21. 【intellij idea】Project Structure 讲解
    一个多maven项目聚合的实例
    解决Maven项目相互依赖/循环依赖/双向依赖的问题
    20. idea刷新项目、清除项目缓存
  • 原文地址:https://www.cnblogs.com/chuncn/p/2050600.html
Copyright © 2020-2023  润新知