86

可能重复的嵌套元素

我从服务器端 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。我究竟做错了什么?

4

12 回答 12

149

使用 .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());
    });
});
于 2013-07-18T13:04:08.447 回答
44

试试这个(演示链接更新):

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 的小提琴演示

于 2013-07-18T13:07:26.803 回答
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)
    ); 
});  
于 2013-07-18T20:56:34.027 回答
8

试试这样:

$.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/

于 2013-07-18T13:01:46.103 回答
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(""));
}
于 2013-07-18T13:04:56.480 回答
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" );
  }
});
于 2015-08-11T07:35:23.233 回答
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');

结果

在此处输入图像描述

于 2018-05-02T16:48:51.000 回答
2

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

 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>
         
 
    
    
    

于 2019-03-05T00:36:07.247 回答
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);
}
;
于 2016-11-07T04:42:35.100 回答
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>
于 2017-08-15T12:56:03.107 回答
0

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

于 2013-07-18T13:05:20.330 回答
0

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

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

如果您使用 dataType 作为 Text 那么您需要 $.parseJSON(response)

于 2017-10-04T08:47:27.340 回答