开发者

Appending ajaxed JSON to existing table

开发者 https://www.devze.com 2023-03-08 05:40 出处:网络
http://jsfiddle.net/mplungjan/LPGeV/ What am I missing here and is there a more elegant way to get at the response data?

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消