Appending ajaxed JSON to existing table
http://jsfiddle.net/mplungjan/LPGeV/
What am I missing here and is there a more elegant way to get at the response data?
$.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);
});
}
);
UPDATE: This works:
function(response) {
$.each(response.rows,function() { // rows
var row = '<tr><td>'+this.cell1+'</td><td>'+this.cell2+'</td></tr>';
$('#tableID').append(row);
});
}
You should set the datatype to 'json' (or use `.getJSON()´, then jQuery will parse the answer for you. (EDIT: Actually jQuery already recognizes the response as JSON and parses for you, so you don't need to parse anyway.)
And since the response data is plain JavaScript objects, it would make sense not the wrap it in jQuery, but use jQuerys "other" .each()
method:
$.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);
});
}
);
EDIT: And you need to loop over response.rows
and nor response
. And Geoff is correct, too.
http://jsfiddle.net/LPGeV/15/
I can't get jsfiddle to load, but you want to append to the tbody, not to the table.
$('#tableID > tbody:last').append(row);
精彩评论