将JSON数组转换为jQuery中的HTML表格
有一个非常简单的方法,我可以把一个JSON对象的数组,并将其转换成一个HTML表,不包括几个字段? 或者我将不得不手动做这个?
我不知道这是你想要的,但有jqGrid 。 它可以接收JSON并创build一个网格。
使用jQuery将使这更简单。
以下将采取一组数组和商店将它们转换成行和单元格。
$.getJSON(url , function(data) { var tbl_body = ""; var odd_even = false; $.each(data, function() { var tbl_row = ""; $.each(this, function(k , v) { tbl_row += "<td>"+v+"</td>"; }) tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>"; odd_even = !odd_even; }) $("#target_table_id tbody").html(tbl_body); });
您可以添加一个检查您想要排除的键通过添加类似
var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };
在getJSON cbf的开始处添加
if ( ( k in expected_keys ) && expected_keys[k] ) { ... }
围绕着tbl_row + =行。
编辑:以前分配一个空variables
编辑:基于Timmmm的无注入贡献的版本。
$.getJSON(url , function(data) { var tbl_body = document.createElement("tbody"); var odd_even = false; $.each(data, function() { var tbl_row = tbl_body.insertRow(); tbl_row.className = odd_even ? "odd" : "even"; $.each(this, function(k , v) { var cell = tbl_row.insertCell(); cell.appendChild(document.createTextNode(v.toString())); }) odd_even = !odd_even; }) $("#target_table_id").appendChild(tbl_body); });
如下所示,通过扩展$来从对象的JSON数组中创buildHTML表
$.makeTable = function (mydata) { var table = $('<table border=1>'); var tblHeader = "<tr>"; for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>"; tblHeader += "</tr>"; $(tblHeader).appendTo(table); $.each(mydata, function (index, value) { var TableRow = "<tr>"; $.each(value, function (key, val) { TableRow += "<td>" + val + "</td>"; }); TableRow += "</tr>"; $(table).append(TableRow); }); return ($(table)); };
并使用如下:
var mydata = eval(jdata); var table = $.makeTable(mydata); $(table).appendTo("#TableCont");
TableCont是一些div
纯粹的HTML方式,不像其他人那样脆弱AFAIK:
// Function to create a table as a child of el. // data must be an array of arrays (outer array is rows). function tableCreate(el, data) { var tbl = document.createElement("table"); tbl.style.width = "70%"; for (var i = 0; i < data.length; ++i) { var tr = tbl.insertRow(); for(var j = 0; j < data[i].length; ++j) { var td = tr.insertCell(); td.appendChild(document.createTextNode(data[i][j].toString())); } } el.appendChild(tbl); }
用法示例:
$.post("/whatever", { somedata: "test" }, null, "json") .done(function(data) { rows = []; for (var i = 0; i < data.Results.length; ++i) { cells = []; cells.push(data.Results[i].A); cells.push(data.Results[i].B); rows.push(cells); } tableCreate($("#results")[0], rows); });
将2D JavaScript数组转换为HTML表格
要将2D JavaScript数组转换为HTML表格,您只需要一点点代码:
function arrayToTable(tableData) { var table = $('<table></table>'); $(tableData).each(function (i, rowData) { var row = $('<tr></tr>'); $(rowData).each(function (j, cellData) { row.append($('<td>'+cellData+'</td>')); }); table.append(row); }); return table; } $('body').append(arrayToTable([ ["John","Slegers",34], ["Tom","Stevens",25], ["An","Davies",28], ["Miet","Hansen",42], ["Eli","Morris",18] ]));
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
对于非常高级的JSON对象到HTML表,你可以尝试我的基于这个闭合线程的 jQuery解决scheme 。
var myList=[{"name": "abc","age": 50},{"name": {"1": "piet","2": "jan","3": "klaas"},"age": "25","hobby": "watching tv"},{"name": "xyz","hobby": "programming","subtable": [{"a": "a","b": "b"},{"a": "a","b": "b"}]}]; // Builds the HTML Table out of myList json data from Ivy restful service. function buildHtmlTable() { addTable(myList, $("#excelDataTable")); } function addTable(list, appendObj) { var columns = addAllColumnHeaders(list, appendObj); for (var i = 0; i < list.length; i++) { var row$ = $('<tr/>'); for (var colIndex = 0; colIndex < columns.length; colIndex++) { var cellValue = list[i][columns[colIndex]]; if (cellValue == null) { cellValue = ""; } if (cellValue.constructor === Array) { $a = $('<td/>'); row$.append($a); addTable(cellValue, $a); } else if (cellValue.constructor === Object) { var array = $.map(cellValue, function (value, index) { return [value]; }); $a = $('<td/>'); row$.append($a); addObject(array, $a); } else { row$.append($('<td/>').html(cellValue)); } } appendObj.append(row$); } } function addObject(list, appendObj) { for (var i = 0; i < list.length; i++) { var row$ = $('<tr/>'); var cellValue = list[i]; if (cellValue == null) { cellValue = ""; } if (cellValue.constructor === Array) { $a = $('<td/>'); row$.append($a); addTable(cellValue, $a); } else if (cellValue.constructor === Object) { var array = $.map(cellValue, function (value, index) { return [value]; }); $a = $('<td/>'); row$.append($a); addObject(array, $a); } else { row$.append($('<td/>').html(cellValue)); } appendObj.append(row$); } } // Adds a header row to the table and returns the set of columns. // Need to do union of keys from all records as some records may not contain // all records function addAllColumnHeaders(list, appendObj) { var columnSet = []; var headerTr$ = $('<tr/>'); for (var i = 0; i < list.length; i++) { var rowHash = list[i]; for (var key in rowHash) { if ($.inArray(key, columnSet) == -1) { columnSet.push(key); headerTr$.append($('<th/>').html(key)); } } } appendObj.append(headerTr$); return columnSet; }
您可以使用接受JSON数据的jQuery插件来填充表格。 jsonTable
我发现在这里重复: 转换json数据到一个html表格
那么,有很多插件存在,包括商业(做这个商业项目?!有点过头…但你可以在这里结帐: https : //github.com/alfajango/jquery-dynatable )
这个有更多的分支: https : //github.com/afshinm/Json-to-HTML-Table
//Example data, Object var objectArray = [{ "Total": "34", "Version": "1.0.4", "Office": "New York" }, { "Total": "67", "Version": "1.1.0", "Office": "Paris" }]; //Example data, Array var stringArray = ["New York", "Berlin", "Paris", "Marrakech", "Moscow"]; //Example data, nested Object. This data will create nested table also. var nestedTable = [{ key1: "val1", key2: "val2", key3: { tableId: "tblIdNested1", tableClassName: "clsNested", linkText: "Download", data: [{ subkey1: "subval1", subkey2: "subval2", subkey3: "subval3" }] } }];
应用代码
//Only first parameter is required var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download');
或者你也可能要检出这个jQuery插件: https : //github.com/jongha/jquery-jsontotable
我认为jongha的插件更容易使用
<div id="jsontotable" class="jsontotable"></div> var data = [[1, 2, 3], [1, 2, 3]]; $.jsontotable(data, { id: '#jsontotable', header: false });
修改@ Dr.sai的代码的位代码。 希望这会有用。
(function ($) { /** * data - array of record * hidecolumns, array of fields to hide * usage : $("selector").generateTable(json, ['field1', 'field5']); */ 'use strict'; $.fn.generateTable = function (data, hidecolumns) { if ($.isArray(data) === false) { console.log('Invalid Data'); return; } var container = $(this), table = $('<table>'), tableHead = $('<thead>'), tableBody = $('<tbody>'), tblHeaderRow = $('<tr>'); $.each(data, function (index, value) { var tableRow = $('<tr>').addClass(index%2 === 0 ? 'even' : 'odd'); $.each(value, function (key, val) { if (index == 0 && $.inArray(key, hidecolumns) <= -1 ) { var theaddata = $('<th>').text(key); tblHeaderRow.append(theaddata); } if ($.inArray(key, hidecolumns) <= -1 ) { var tbodydata = $('<td>').text(val); tableRow.append(tbodydata); } }); $(tableBody).append(tableRow); }); $(tblHeaderRow).appendTo(tableHead); tableHead.appendTo(table); tableBody.appendTo(table); $(this).append(table); return this; }; })(jQuery);
希望这将有助于隐藏一些专栏。 链接到文件
用纯jquery:
window.jQuery.ajax({ type: "POST", url: ajaxUrl, contentType: 'application/json', success: function (data) { var odd_even = false; var response = JSON.parse(data); var head = "<thead class='thead-inverse'><tr>"; $.each(response[0], function (k, v) { head = head + "<th scope='row'>" + k.toString() + "</th>"; }) head = head + "</thead></tr>"; $(table).append(head);//append header var body="<tbody><tr>"; $.each(response, function () { body=body+"<tr>"; $.each(this, function (k, v) { body=body +"<td>"+v.toString()+"</td>"; }) body=body+"</tr>"; }) body=body +"</tbody>"; $(table).append(body);//append body }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.responsetext); } });
更短的方式
$.makeTable = function (mydata) { if (mydata.length <= 0) return ""; return $('<table border=1>').append("<tr>" + $.map(mydata[0], function (val, key) { return "<th>" + key + "</th>"; }).join("\n") + "</tr>").append($.map(mydata, function (index, value) { return "<tr>" + $.map(index, function (val, key) { return "<td>" + val + "</td>"; }).join("\n") + "</tr>"; }).join("\n")); };