1

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

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Hmm, the example I looked at was just looping over response, I assumed it would do something like for (o in response) which would be rows. The datatype seems not to matter in Fx at least.
2

I can't get jsfiddle to load, but you want to append to the tbody, not to the table.

$('#tableID > tbody:last').append(row);

1 Comment

I have appended to the table before and it works just fine: jsfiddle.net/mplungjan/DLaRw

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.