问题描述
|
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中而不使用jQuerys“ other \”
.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
。而且杰夫也是正确的。
http://jsfiddle.net/LPGeV/15/
,我无法加载jsfiddle,但是您想要附加到tbody,而不是附加到表。
$(\'#tableID > tbody:last\').append(row);