使用jQuery从AJAX响应构建表行(json)


77

可能重复的嵌套元素

我从服务器端ajax响应(Json)中获取信息,并试图动态创建表行并将其附加到ID =的现有表中records_table

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

我的回答如下:

    '[{
      "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,所以我尝试做以下事情,这当然是灾难:

    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的一行。我究竟做错了什么?

Answers:


139

使用.append而不是.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());
    });
});

1
这个工作,使管理td要素干净
路易斯Siquot

2
我更新了解决方案。您需要使用jQuery的$ .parseJSON函数将字符串转换为JSON。jsfiddle.net/abduncan/rrzZU/1
drizzie

3
对于大型数据,使用jQuery附加数据不是一个好主意。您将最终遇到浏览器渲染问题。相反,我们可以使用join()生成截断的字符串来显示
shivg

1
嗨,但是,此响应如何将此信息添加到html #recordsTable中呢?
GoldenEagle

2
如果从包含注释的底部开始看第四行//.appendTo('#records_table');,它将显示如何将记录追加到DOM。在此答案中将其注释掉,并将结果写入控制台以进行测试。
drizzie '16

41

试试这个(DEMO链接已更新):

success: function (response) {
        var trHTML = '';
        $.each(response, function (i, item) {
            trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
        });
        $('#records_table').append(trHTML);
    }

小提琴演示与AJAX


@Charlesliam Glad可以帮助您.. :)
Neeraj Singh

@NeerajSingh链接已损坏
Code-EZ

2
链接已过期。
Abhishek Pandey,

无论如何,TD包含CSS?
Aroon

@alper感谢您的评论,演示链接现已更新。
Neeraj Singh,

11

这是hmkcode.com的完整答案

如果我们有这样的JSON数据

// JSON Data
var articles = [
    { 
        "title":"Title 1",
        "url":"URL 1",
        "categories":["jQuery"],
        "tags":["jquery","json","$.each"]
    },
    {
        "title":"Title 2",
        "url":"URL 2",
        "categories":["Java"],
        "tags":["java","json","jquery"]
    }
];

我们要查看此表结构

<table id="added-articles" class="table">
            <tr>
                <th>Title</th>
                <th>Categories</th>
                <th>Tags</th>
            </tr>
        </table>

以下JS代码将为每个JSON元素填充创建一行

// 1. remove all existing rows
$("tr:has(td)").remove();

// 2. get each article
$.each(articles, function (index, article) {

    // 2.2 Create table column for categories
    var td_categories = $("<td/>");

    // 2.3 get each category of this article
    $.each(article.categories, function (i, category) {
        var span = $("<span/>");
        span.text(category);
        td_categories.append(span);
    });

    // 2.4 Create table column for tags
   var td_tags = $("<td/>");

    // 2.5 get each tag of this article    
    $.each(article.tags, function (i, tag) {
        var span = $("<span/>");
        span.text(tag);
        td_tags.append(span);
    });

    // 2.6 Create a new row and append 3 columns (title+url, categories, tags)
    $("#added-articles").append($('<tr/>')
            .append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>"))
            .append(td_categories)
            .append(td_tags)
    ); 
});  

该示例不再可用,404。“这是hmkcode.com的完整答案”
RaRdEvA

7

像这样尝试:

$.each(response, function(i, item) {
    $('<tr>').html("<td>" + response[i].rank + "</td><td>" + response[i].content + "</td><td>" + response[i].UID + "</td>").appendTo('#records_table');
});

演示:http//jsfiddle.net/R5bQG/


可以改善吗?我也想对单元格进行控制,例如,如果要在td中设置属性。
Canttouchit

当然,您可以通过多种方式执行此操作,可以构建每个TD,然后追加,也可以直接在上面的标签中设置属性。您要添加什么属性,请提供示例。
tymeJV

我认为这不起作用,因为我的回复回复是字符串形式"[{ "rank":"9", "content":"Alon", "UID":"5" }, { "rank":"6", "content":"Tala", "UID":"6" }]"
Canttouchit

4

您不应该为每个单元格和行创建jquery对象。试试这个:

function responseHandler(response)
{
     var c = [];
     $.each(response, function(i, item) {             
         c.push("<tr><td>" + item.rank + "</td>");
         c.push("<td>" + item.content + "</td>");
         c.push("<td>" + item.UID + "</td></tr>");               
     });

     $('#records_table').html(c.join(""));
}

4
$.ajax({
  type: 'GET',
  url: urlString ,
  dataType: 'json',
  success: function (response) {
    var trHTML = '';
    for(var f=0;f<response.length;f++) {
      trHTML += '<tr><td><strong>' + response[f]['app_action_name']+'</strong></td><td><span class="label label-success">'+response[f]['action_type'] +'</span></td><td>'+response[f]['points']+'</td></tr>';
     }
    $('#result').html(trHTML); 
    $( ".spin-grid" ).removeClass( "fa-spin" );
  }
});

3

数据为JSON

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

您可以使用jQuery遍历JSON并动态创建表:

num_rows = data.length;
num_cols = size_of_array(data[0]);

table_id = 'my_table';
table = $("<table id=" + table_id + "></table>");

header = $("<tr class='table_header'></tr>");
$.each(Object.keys(data[0]), function(ind_header, val_header) {
col = $("<td>" + val_header + "</td>");
header.append(col);
})
table.append(header);

$.each(data, function(ind_row, val) {
row = $("<tr></tr>");
$.each(val, function(ind_cell, val_cell) {
col = $("<td>" + val_cell + "</td>");
row.append(col);
})
table.append(row);
})

这是size_of_array函数:

function size_of_array(obj) {
    size = Object.keys(obj).length;
    return(size)
    };

您还可以根据需要添加样式

$('.' + content['this_class']).children('canvas').remove();
$('.' + content['this_class']).append(table);
$('#' + table_id).css('width', '100%').css('border', '1px solid black').css('text-align', 'center').css('border-collapse', 'collapse');
$('#' + table_id + ' td').css('border', '1px solid black');

结果

在此处输入图片说明


1

我已经创建了这个JQuery函数

/**
 * Draw a table from json array
 * @param {array} json_data_array Data array as JSON multi dimension array
 * @param {array} head_array Table Headings as an array (Array items must me correspond to JSON array)
 * @param {array} item_array JSON array's sub element list as an array
 * @param {string} destinaion_element '#id' or '.class': html output will be rendered to this element
 * @returns {string} HTML output will be rendered to 'destinaion_element'
 */

function draw_a_table_from_json(json_data_array, head_array, item_array, destinaion_element) {
    var table = '<table>';
    //TH Loop
    table += '<tr>';
    $.each(head_array, function (head_array_key, head_array_value) {
        table += '<th>' + head_array_value + '</th>';
    });
    table += '</tr>';
    //TR loop
    $.each(json_data_array, function (key, value) {

        table += '<tr>';
        //TD loop
        $.each(item_array, function (item_key, item_value) {
            table += '<td>' + value[item_value] + '</td>';
        });
        table += '</tr>';
    });
    table += '</table>';

    $(destinaion_element).append(table);
}
;

1

您可以这样做:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


    <script>
    $(function(){

    $.ajax({
    url: '<Insert your REST API which you want GET/POST/PUT/DELETE>',
    data: '<any parameters you want to send as the Request body or query string>',
    dataType: json,
    async: true,
    method: "GET"
    success: function(data){

    //If the REST API returned a successful response it'll be stored in data, 
    //just parse that field using jQuery and you're all set

    var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>';

    $.each(data, function(idx, obj){

    //Outer .each loop is for traversing the JSON rows
    tblSomething += '<tr>';

    //Inner .each loop is for traversing JSON columns
    $.each(obj, function(key, value){
    tblSomething += '<td>' + value + '</td>';
    });
    tblSomething += '</tr>';
    });

    tblSomething += '</tbody>';

    $('#tblSomething').html(tblSomething);
    },
    error: function(jqXHR, textStatus, errorThrown){
    alert('Hey, something went wrong because: ' + errorThrown);
    }
    });


    });
    </script>


    <table id = "tblSomething" class = "table table-hover"></table>

0

jQuery.html将字符串或回调作为输入,不确定示例的工作方式...尝试类似的操作$('<tr>').append($('<td>' + item.rank + '</td>').append ... 并且您在标签来源方面存在一定的问题。应该是$('<tr/>')$('<td/>')


0

我执行以下操作以从Ajax获取JSON响应并在不使用parseJson的情况下进行解析:

$.ajax({
  dataType: 'json', <----
  type: 'GET',
  url: 'get/allworldbankaccounts.json',
  data: $("body form:first").serialize(),

如果将dataType用作Text,则需要$ .parseJSON(response)


0

这是我从项目中复制的工作示例。

 function fetchAllReceipts(documentShareId) {

        console.log('http call: ' + uri + "/" + documentShareId)
        $.ajax({
            url: uri + "/" + documentShareId,
            type: "GET",
            contentType: "application/json;",
            cache: false,
            success: function (receipts) {
                //console.log(receipts);

                $(receipts).each(function (index, item) {
                    console.log(item);
                    //console.log(receipts[index]);

                    $('#receipts tbody').append(
                        '<tr><td>' + item.Firstname + ' ' + item.Lastname +
                        '</td><td>' + item.TransactionId +
                        '</td><td>' + item.Amount +
                        '</td><td>' + item.Status + 
                        '</td></tr>'
                    )

                });


            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);

            }

        });
    }
    
    
    // Sample json data coming from server
    
    var data =     [
    0: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test1", Lastname: "Test1", }
    1: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test 2", Lastname: "Test2", }
];
  <button type="button" class="btn btn-primary" onclick='fetchAllReceipts("@share.Id")'>
                                        RECEIPTS
                                    </button>
 
 <div id="receipts" style="display:contents">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Transaction</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
         </div>
         
 
    
    
    


我使用您唯一的追加块,我正在以自举模式显示数据,问题是它每次都在追加,也在以前的数据上追加。
阿里·拉扎
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.