JSON data from AJAX script is not appearing in HTML table
Here is my code:
$(document).ready(function () {
$.ajax({
url: '/blog/getposts',
type:开发者_开发知识库 'GET',
dataType: 'json',
success: function (result) {
var insert = '';
$.each(result, function (index, item) {
insert += '<tr><td>' + item.Name + '</td><td>' + item.Body + '</td><td>' + item.DateCreated + '</td></tr>';
});
$('#blogTable').append(insert);
}
});
});
It works when I don't try to insert any <tr>
or <td>
tags but nothing appears when I do include those tags. I also have Firebug but I don't know what to look for.
I want to display a table with headers for Name, Body, and DateCreated, then all the data for each entry listed below.
EDIT: my JSON results
[
{"PostId":4,"UserId":2,"Body":"testtat","DateCreated":"\/Date(1301692095627)\/","Name":"derper"},
{"PostId":3,"UserId":2,"Body":"tesateat","DateCreated":"\/Date(1301692093497)\/","Name":"derper"},
{"PostId":2,"UserId":2,"Body":"testest","DateCreated":"\/Date(1301692091527)\/","Name":"derper"},
{"PostId":1,"UserId":2,"Body":"derprperp","DateCreated":"\/Date(1301692082100)\/","Name":"derper"}
]
EDIT: The InnerHTML paste from FireBug
<tbody><tr>
<th>Name</th>
<th>Body</th>
<th>Date</th>
</tr>
EDIT: So this is my html:
<table id="blogTable">
<tr>
<th>Name</th>
<th>Body</th>
<th>Date</th>
</tr>
If i change my insert to this:
insert +=
'<td>'
+ item.Name +'</td><td>'
+ item.Body +'</td><td>'
+ item.DateCreated +'</td>'
;
then the innerhtml output when i run the site is:
<tbody><tr>
<th>Name</th>
<th>Body</th>
<th>Date</th>
</tr>
</tbody>
<td>derper</td><td>testtat</td><td>/Date(1301692095627)/</td>
<td>derper</td><td>tesateat</td><td>/Date(1301692093497)/</td>
<td>derper</td><td>testest</td><td>/Date(1301692091527)/</td>
<td>derper</td><td>derprperp</td><td>/Date(1301692082100)/</td>
so my problem is when I'm trying to add new rows, they don't show up, but when I just use cells (<td>
), they show up. How can I add new <tr>
's into the <tbody>
?
The code you've posted, so far, works. See: jsfiddle.net/SQVz6/ .
Using Firebug, inspect table: blogTable
. (Right-clicking on the table will usually show Firebug's "Inspect" tool in the context menu.)
~~~~~~~
Does the table structure look right?
Right-click on <table id="blogTable">
in the inspector and then click Copy innerHTML
Paste the results into your question, above.
Try changing .append()
to .appendTo()
?
after many hours of trying to figure out a solution, i changed the insert statement to this:
$('#blogTable tr:last').after(insert);
and it works now. innerHTML output came out as follows:
<tbody>
<tr>
<th>Name</th>
<th>Body</th>
<th>Date</th>
</tr>
<tr>
<td>derper</td>
<td>testtat</td>
<td>/Date(1301692095627)/</td>
</tr>
<tr>
<td>derper</td>
<td>tesateat</td>
<td>/Date(1301692093497)/</td>
</tr>
<tr>
<td>derper</td>
<td>testest</td>
<td>/Date(1301692091527)/</td>
</tr>
<tr>
<td>derper</td>
<td>derprperp</td>
<td>/Date(1301692082100)/</td>
</tr>
</tbody>
精彩评论