Converting JSON Arrays to HTML Tables with jQuery
Transforming an array of JSON objects into an HTML table can be accomplished efficiently using jQuery.
Solution:
The provided jQuery code snippet converts an array of JSON objects into an HTML table, excluding specific fields:
<pre class="brush:php;toolbar:false"> $.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); });
To exclude specific keys, add this logic before the tbl_row = line:
var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true }; if ( ( k in expected_keys ) && expected_keys[k] ) { ... }
Alternatively, a more secure and DOM-friendly approach can be used:
<pre class="brush:php;toolbar:false"> $.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").append(tbl_body); //DOM table doesn't have .appendChild });
These methods allow you to easily convert JSON arrays into HTML tables, with the flexibility to exclude unwanted fields.
The above is the detailed content of How to Convert JSON Arrays into HTML Tables with jQuery, Including the Ability to Exclude Specific Fields?. For more information, please follow other related articles on the PHP Chinese website!