2011-05-24 49 views
1

http://jsfiddle.net/mplungjan/LPGeV/追加ajaxed JSON到现有的表

缺少什么我在这里,是有更优雅的方式来获得的响应数据?

$.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:这工作:

function(response) { 
    $.each(response.rows,function() { // rows 
     var row = '<tr><td>'+this.cell1+'</td><td>'+this.cell2+'</td></tr>'; 
     $('#tableID').append(row); 
    });        
} 

回答

3

你应该设置的数据类型为“JSON”(或使用`.getJSON()',然后jQuery将解析为你解答(编辑:其实jQuery的已识别的响应作为JSON并解析为您,所以你不需要反正解析)

而且由于响应数据是纯JavaScript对象,它将使jQuery的意义不是包的,而是用jQuerys“其他” .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/

+0

谢谢!嗯,我看到的例子只是循环回应,我认为它会做一些类似于(o的回应),这将是行。至少在Fx中数据类型似乎不重要。 – mplungjan 2011-05-24 16:47:56

2

我不能得到的jsfiddle加载,但要附加到TBODY,不表。

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

我已经追加到表之前,它工作得很好:http://jsfiddle.net/mplungjan/DLaRw/ – mplungjan 2011-05-24 16:47:01