Using jQuery to build table rows from AJAX response(json)
Use .append instead of .html
var response = "[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]";
// convert string to JSON
response = $.parseJSON(response);
$(function() {
$.each(response, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.rank),
$('<td>').text(item.content),
$('<td>').text(item.UID)
); //.appendTo('#records_table');
console.log($tr.wrap('<p>').html());
});
});
Try this (DEMO link updated):
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
});
$('#records_table').append(trHTML);
}
Fiddle DEMO WITH AJAX
Here is a complete answer from hmkcode.com
If we have such JSON data
// JSON Data
var articles = [
{
"title":"Title 1",
"url":"URL 1",
"categories":["jQuery"],
"tags":["jquery","json","$.each"]
},
{
"title":"Title 2",
"url":"URL 2",
"categories":["Java"],
"tags":["java","json","jquery"]
}
];
And we want to view in this Table structure
<table id="added-articles" class="table">
<tr>
<th>Title</th>
<th>Categories</th>
<th>Tags</th>
</tr>
</table>
The following JS code will fill create a row for each JSON element
// 1. remove all existing rows
$("tr:has(td)").remove();
// 2. get each article
$.each(articles, function (index, article) {
// 2.2 Create table column for categories
var td_categories = $("<td/>");
// 2.3 get each category of this article
$.each(article.categories, function (i, category) {
var span = $("<span/>");
span.text(category);
td_categories.append(span);
});
// 2.4 Create table column for tags
var td_tags = $("<td/>");
// 2.5 get each tag of this article
$.each(article.tags, function (i, tag) {
var span = $("<span/>");
span.text(tag);
td_tags.append(span);
});
// 2.6 Create a new row and append 3 columns (title+url, categories, tags)
$("#added-articles").append($('<tr/>')
.append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>"))
.append(td_categories)
.append(td_tags)
);
});