使用jQuery从Ajax响应(Json)构建表行

时间:2022-10-07 17:05:20

Possible duplicate Nested elements

可能重复嵌套的元素

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);

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

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

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

My response looks like that:

我的回答是:

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

the require result is something like that:

要求的结果是这样的:

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

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

我想在不解析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');

            });
        });


    }

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

从我的解中,所有单元格中只有一行是6。我做错了什么?

11 个解决方案

#1


87  

Use .append instead of .html

使用.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());
    });
});

#2


29  

Try this:

试试这个:

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);
    }

Fiddle DEMO WITH AJAX

使用AJAX小提琴演示

#3


7  

Here is a complete answer from hmkcode.com

这是来自hmkcode.com的完整答案。

If we have such JSON data

如果我们有这样的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"]
    }
];

And we want to view in this Table structure

我们想看看这个表格结构

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

The following JS code will fill create a row for each JSON element

下面的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)
    ); 
});  

#4


5  

Try it like this:

试试这样:

$.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');
});

Demo: http://jsfiddle.net/R5bQG/

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

#5


3  

You shouldn't create jquery objects for each cell and row. Try this:

不应该为每个单元格和行创建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(""));
}

#6


3  

$.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" );
  }
});

#7


1  

I have created this JQuery function

我创建了这个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);
}
;

#8


1  

You could do it something like this:

你可以这样做:

<!-- 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>

#9


0  

jQuery.html takes string or callback as input, not sure how your example is working... Try something like $('<tr>').append($('<td>' + item.rank + '</td>').append ... And you have some definite problems with tags fromation. It should be $('<tr/>') and $('<td/>')

jQuery。html接受字符串或回调作为输入,不确定示例如何工作……尝试像美元(“< tr >”)。追加($(' < td > ' +项目。等级+ < / td >)。添加……你对标签从定义有一些明确的问题。应该是$('')和$('')

#10


0  

I do following to get JSON response from Ajax and parse without using parseJson:

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

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

If you are using dataType as Text then you need $.parseJSON(response)

如果使用数据类型作为文本,则需要$.parseJSON(response)

#11


0  

Data as JSON:

JSON数据:

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

You can use jQuery to iterate over JSON and create tables dynamically:

可以使用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);
})

Here is the size_of_array function:

下面是size_of_array函数:

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

You can also add styling if needed:

如果需要,还可以添加样式:

$('.' + 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');

Result:

结果:

使用jQuery从Ajax响应(Json)构建表行

Of course you can instead use a library that does these things for you. For example, in Kedion you simply add JSON to the add_visual function:

当然,你可以使用一个库来为你做这些事情。例如,在Kedion中,只需向add_visual函数添加JSON:

add_visual("target_class", 1, {
        "this_class" : "my_visual",
        "type" : "table",
        "width" : "500px",
        "height" : "300px",
        "data" : data // your data object here
        })

Or you can simply grab the JSON from your URL and use it with your library of choice:

或者,您可以从URL中获取JSON并将其与您所选择的库一起使用:

$.getJSON('https://raw.githubusercontent.com/domoritz/maps/master/data/iris.json', function(data) {
  add_visual("my_sections", 6, {
        "this_class" : "my_visual",
        "type" : "table",
        "width" : "90%",
        "height" : "300px",
        "data_color" : "#33AADE",
        "data" : data
        })
   style_visual('my_visual', 1, {
   "font-family" : "arial"
   })
   });

使用jQuery从Ajax响应(Json)构建表行

#1


87  

Use .append instead of .html

使用.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());
    });
});

#2


29  

Try this:

试试这个:

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);
    }

Fiddle DEMO WITH AJAX

使用AJAX小提琴演示

#3


7  

Here is a complete answer from hmkcode.com

这是来自hmkcode.com的完整答案。

If we have such JSON data

如果我们有这样的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"]
    }
];

And we want to view in this Table structure

我们想看看这个表格结构

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

The following JS code will fill create a row for each JSON element

下面的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)
    ); 
});  

#4


5  

Try it like this:

试试这样:

$.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');
});

Demo: http://jsfiddle.net/R5bQG/

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

#5


3  

You shouldn't create jquery objects for each cell and row. Try this:

不应该为每个单元格和行创建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(""));
}

#6


3  

$.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" );
  }
});

#7


1  

I have created this JQuery function

我创建了这个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);
}
;

#8


1  

You could do it something like this:

你可以这样做:

<!-- 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>

#9


0  

jQuery.html takes string or callback as input, not sure how your example is working... Try something like $('<tr>').append($('<td>' + item.rank + '</td>').append ... And you have some definite problems with tags fromation. It should be $('<tr/>') and $('<td/>')

jQuery。html接受字符串或回调作为输入,不确定示例如何工作……尝试像美元(“< tr >”)。追加($(' < td > ' +项目。等级+ < / td >)。添加……你对标签从定义有一些明确的问题。应该是$('')和$('')

#10


0  

I do following to get JSON response from Ajax and parse without using parseJson:

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

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

If you are using dataType as Text then you need $.parseJSON(response)

如果使用数据类型作为文本,则需要$.parseJSON(response)

#11


0  

Data as JSON:

JSON数据:

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

You can use jQuery to iterate over JSON and create tables dynamically:

可以使用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);
})

Here is the size_of_array function:

下面是size_of_array函数:

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

You can also add styling if needed:

如果需要,还可以添加样式:

$('.' + 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');

Result:

结果:

使用jQuery从Ajax响应(Json)构建表行

Of course you can instead use a library that does these things for you. For example, in Kedion you simply add JSON to the add_visual function:

当然,你可以使用一个库来为你做这些事情。例如,在Kedion中,只需向add_visual函数添加JSON:

add_visual("target_class", 1, {
        "this_class" : "my_visual",
        "type" : "table",
        "width" : "500px",
        "height" : "300px",
        "data" : data // your data object here
        })

Or you can simply grab the JSON from your URL and use it with your library of choice:

或者,您可以从URL中获取JSON并将其与您所选择的库一起使用:

$.getJSON('https://raw.githubusercontent.com/domoritz/maps/master/data/iris.json', function(data) {
  add_visual("my_sections", 6, {
        "this_class" : "my_visual",
        "type" : "table",
        "width" : "90%",
        "height" : "300px",
        "data_color" : "#33AADE",
        "data" : data
        })
   style_visual('my_visual', 1, {
   "font-family" : "arial"
   })
   });

使用jQuery从Ajax响应(Json)构建表行