javascript - 将 ajaxed JSON 附加到现有表

标签 javascript jquery json

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 中是有意义的,而是使用 jQuery 的“其他”.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.rowsresponse。杰夫也是正确的。

http://jsfiddle.net/LPGeV/15/

关于javascript - 将 ajaxed JSON 附加到现有表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6111937/

相关文章:

javascript - ajax 上的 get 函数内部出现未定义错误

javascript - jQuery UI 滑动效果新建一行

javascript - 需要一些创意 DOM 抓取确认框的想法

javascript - 将 json 对象合并到数据表中

json - Angular 2 : Access object data

java - 将对象转换为 Java 中的自定义 DTO 列表

javascript - 当他们说 JavaScript 是单线程的时,这是什么意思?

javascript - 事件委托(delegate)和循环遍历 if 语句中的元素

javascript - jquery ui 弄乱了工具提示

javascript - 使用 javascript 通过 google api 发送邮件失败