Render Json data to HTML
Hi Guys today i will demonstrate how to render the Json data to ui.
<script>
$.ajax({
url: '/echo/json/',
type: "post",
dataType: "json",
data: {
json: JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]),
delay: 3
},
success: function(data, textStatus, jqXHR) {
// since we are using jQuery, you don't need to parse response
drawTable(data);
}
});
/**iterates json array*** /
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
/**print json object on ui**/
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
}
</script>
UI Part
________________________________________________________________________
<table id="personDataTable">
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</table>
<script>
$.ajax({
url: '/echo/json/',
type: "post",
dataType: "json",
data: {
json: JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]),
delay: 3
},
success: function(data, textStatus, jqXHR) {
// since we are using jQuery, you don't need to parse response
drawTable(data);
}
});
/**iterates json array*** /
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
/**print json object on ui**/
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
}
</script>
UI Part
________________________________________________________________________
<table id="personDataTable">
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</table>
0 comments: