http://jsfiddle.net/mplungjan/LPGeV/
我在这里遗漏了什么,是否有更优雅的方式来获取响应数据?
$.post('/echo/json/',{
"json": JSON.stringify({
"rows": [
{
"cell1":"row 2 cell 1",
"cell2":"row 2 cell 2"
},
{
"cell1":"row 3 cell 1",
"cell2":"row 3 cell 2"
}
]})
},
function(response) {
$response = JSON.parse(response)
$response.each(function() { // rows
var row = '<tr><td>'+$(this).cell1+'</td><td>'+$(this).cell2+'</td></tr>';
$('#tableID').append(row);
});
}
);
更新:这有效:
function(response) {
$.each(response.rows,function() { // rows
var row = '<tr><td>'+this.cell1+'</td><td>'+this.cell2+'</td></tr>';
$('#tableID').append(row);
});
}
最佳答案
您应该将数据类型设置为“json”(或使用“.getJSON()”,然后 jQuery 将为您解析答案。(编辑:实际上 jQuery 已经将响应识别为 JSON 并为您解析,所以您不需要无论如何都需要解析。)
并且由于响应数据是纯 JavaScript 对象,因此不将其包装在 jQuery 中是有意义的,而是使用 jQuery 的“其他”.each()
方法:
$.post('/echo/json/',{
dataType: "json",
"json": JSON.stringify({
"rows": [
{
"cell1":"row 2 cell 1",
"cell2":"row 2 cell 2"
},
{
"cell1":"row 3 cell 1",
"cell2":"row 3 cell 2"
}
]})
},
function(response) {
$.each(response.rows, function() {
var row = '<tr><td>'+ this.cell1+'</td><td>'+ this.cell2+'</td></tr>';
$('#tableID > tbody').append(row);
});
}
);
编辑:您需要遍历 response.rows
和 response
。杰夫也是正确的。
关于javascript - 将 ajaxed JSON 附加到现有表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6111937/