Display JSON Data in HTML Table
Try this:
CSS:
.hidden{display:none;}
HTML:
<table id="table" class="hidden">
<tr>
<th>City</th>
<th>Status</th>
</tr>
</table>
JS:
$('#search').click(function() {
$.ajax({
type: 'POST',
url: 'cityResults.htm',
data: $('#cityDetails').serialize(),
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].city && data[i].cStatus){
txt += "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form submission
});
As an alternative to the answers you already have, and for others that come accross this post. I recently had a similar task and created a small jquery plug in to do it for me. Its pretty small under 3KB minified, and has sorting, paging and the ability to show and hide columns.
It should be pretty easy to customize using css. More information can be found here http://mrjsontable.azurewebsites.net/ and the project is available for you to do as you wish with on github https://github.com/MatchingRadar/Mr.JsonTable
To get it to work download the files and pop them in your site. Follow the instructions and you should end up with something like the following:
<div id="citytable"></div>
Then in the ajax success method you will want something like this
success: function(data){
$("#citytable").mrjsontable({
tableClass: "my-table",
pageSize: 10, //you can change the page size here
columns: [
new $.fn.mrjsontablecolumn({
heading: "City",
data: "city"
}),
new $.fn.mrjsontablecolumn({
heading: "City Status",
data: "cStatus"
})
],
data: data
});
}
Hope it helps somebody else!