使用jQuery从AJAX响应构建表行(json) [英] Using jQuery to build table rows from AJAX response(json)

查看:76
本文介绍了使用jQuery从AJAX响应构建表行(json)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复的嵌套元素

我正在从服务器端ajax响应(Json)获取,并且正在尝试动态创建表行 并将它们附加到现有表(ID:#records_table);

I'm getting from server-side ajax response(Json) and I'm trying to dynamically create table rows and append them to existing table (ID: #records_table);

我试图重复实现该解决方案,但失败了.

I tried to implement the solution in possible duplicate but it failed.

我的回答如下:

    "[{
      "rank":"9",
      "content":"Alon",
      "UID":"5"
     },
     {
       "rank":"6",
       "content":"Tala",
       "UID":"6"
    }]"

需求结果是这样的:

<tr>
   <td>9</td>
   <td>Alon</td>
   <td>5</td>  
</tr>
<tr>
   <td>6</td>
   <td>Tala</td>
   <td>5</td>  
</tr>

我想做一些不解析Json的事情,所以我尝试做以下事情,这当然是一场灾难:

I want to do something without parsing the Json so I tried to do the following, which of course was a disaster:

    function responseHandler(response)
    {

        $(function() {
            $.each(response, function(i, item) {
                $('<tr>').html(
                    $('td').text(item.rank),
                    $('td').text(item.content),
                    $('td').text(item.UID)
                ).appendTo('#records_table');

            });
        });


    }

从我的解决方案中,我在所有单元格中只得到数字为6的一行.我在做什么错了?

From my solution I get only one row with the number 6 in all cells. What am I doing wrong?

推荐答案

使用.append代替.html

Use .append instead of .html

var response = "[{
      "rank":"9",
      "content":"Alon",
      "UID":"5"
     },
     {
       "rank":"6",
       "content":"Tala",
       "UID":"6"
    }]";

// convert string to JSON
response = $.parseJSON(response);

$(function() {
    $.each(response, function(i, item) {
        var $tr = $('<tr>').append(
            $('<td>').text(item.rank),
            $('<td>').text(item.content),
            $('<td>').text(item.UID)
        ); //.appendTo('#records_table');
        console.log($tr.wrap('<p>').html());
    });
});

这篇关于使用jQuery从AJAX响应构建表行(json)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆