使用 jQuery 从 AJAX 响应(json)构建表行 [英] Using jQuery to build table rows from AJAX response(json)
本文介绍了使用 jQuery 从 AJAX 响应(json)构建表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复嵌套元素
我从服务器端 ajax 响应 (Json) 获取,我正在尝试动态创建表行并将它们附加到 id=records_table
的现有表中.
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.
我的回答是这样的:
'[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]'
需要的结果是这样的:
<tr>
<td>9</td>
<td>Alon</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>Tala</td>
<td>5</td>
</tr>
我想在不解析 Json 的情况下做一些事情,所以我尝试执行以下操作,这当然是一场灾难:
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');
});
});
}
从我的解决方案中,我只得到一行,所有单元格中的数字都是 6.我做错了什么?
From my solution I get only one row with the number 6 in all cells. What am I doing wrong?
推荐答案
使用 .append 而不是 .html
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());
});
});
这篇关于使用 jQuery 从 AJAX 响应(json)构建表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文