Reputation: 2679
How to append json
data in table. Json data format {"FirstName":"Cho"
,"LastName":"Chee","Company":"solution"}
. This code did not show data in table as expected.
JQuery Code:
var uri = 'api/Employee/GetData';
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
$.each(data, function (key, item) {
$('<li>', { text: formatItem(item) }).appendTo($("#tbdata"));
});
});
});
function formatItem(item) {
return item.FirstName + ' ' + item.LastName + ' ' + item.Company;
}
HTML table :
<table class="table-bordered table-striped table table-hover" id="tbdata">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Company</th>
</tr>
</table>
Upvotes: 1
Views: 4283
Reputation: 11502
Take a look at below code snippet. I am assuming you will get array of data from your server.
function formatItem(item) {
return '<td>'+item.FirstName + '</td> <td> ' + item.LastName + ' </td><td>' + item.Company+'</td>';
}
var data = [
{"FirstName":"Cho","LastName":"Chee","Company":"solution"},
{"FirstName":"Cho1","LastName":"Chee1","Company":"solution1"},
{"FirstName":"Cho2","LastName":"Chee2","Company":"solution2"},
];
$.each(data, function (key, item) {
$('<tr>', { html: formatItem(item) }).appendTo($("#tbdata"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table class="table-bordered table-striped table table-hover" id="tbdata">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Company</th>
</tr>
</table>
Upvotes: 1
Reputation: 2367
What you need to add are whole table rows with table data cells for each item property. Additionally you want to add this to the table body not to the table as a whole. I would do it like this:
HTML:
<table class="table-bordered table-striped table table-hover">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Company</th>
</tr>
</thead>
<tbody id="tbdata">
<!-- data will go here -->
</tbody>
</table>
Javascript:
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
var html = "";
$.each(data, function (key, item) {
html += formatItem(item);
});
$("#tbdata").append(html);
});
});
function formatItem(item) {
return '<tr><td>' item.FirstName + '</td><td>' + item.LastName + '</td><td>' + item.Company + '</td></tr>';
}
Upvotes: 0