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 an existing table with 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?
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With