Canttouchit Canttouchit - 27 days ago 8
jQuery Question

Using jQuery to build table rows from Ajax response(Json)

Possible duplicate Nested elements

I'm getting from server-side ajax response(Json) and I'm trying to dynamically create table rows
and append them to existing table (ID:

#records_table
);

I tried to implement the solution in possible duplicate but it failed.

My response looks like that:

"[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]"


the require result is something like that:

<tr>
<td>9</td>
<td>Alon</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>Tala</td>
<td>5</td>
</tr>


I want to do something without parsing the Json so I tried to do the following, which of course was a disaster:

function responseHandler(response)
{

$(function() {
$.each(response, function(i, item) {
$('<tr>').html(
$('td').text(item.rank),
$('td').text(item.content),
$('td').text(item.UID)
).appendTo('#records_table');

});
});


}


From my solution I get only one row with the number 6 in all cells. What am I doing wrong?

Answer

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());
    });
});
Comments