Utiliser jQuery pour construire des lignes de table à partir de la réponse Ajax (Json)

possibilité de dupliquer éléments imbriqués

"

j'obtiens de la réponse ajax côté serveur (JSON) et j'essaye de créer dynamiquement des lignes de table et les ajouter à la table existante (ID: #records_table );

j'ai essayé de mettre en œuvre la solution en duplicata possible mais elle a échoué.

ma réponse ressemble à cela:

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

le résultat require est quelque chose comme ça:

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

je veux faire quelque chose sans analyser le Json donc j'ai essayé de faire ce qui suit, qui était bien sûr un désastre:

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

            });
        });


    }

de ma solution je n'obtiens qu'une rangée avec le numéro 6 dans toutes les cellules. Ce que je fais mal?

51
demandé sur Brian Tompsett - 汤莱恩 2013-07-18 16:52:59

11 réponses

utiliser .ajouter au lieu de .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());
    });
});
97
répondu drizzie 2013-07-18 13:34:28

essayez ceci:

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

31
répondu Neeraj Singh 2013-07-18 13:07:26

Voici une réponse complète de hmkcode.com

si nous avons de telles données 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"]
    }
];

et nous voulons voir dans cette structure de tableau

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

le code JS suivant servira à créer une ligne pour chaque élément 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)
    ); 
});  
7
répondu hmkcode 2013-07-18 20:56:34

essayez comme ceci:

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

Démo: http://jsfiddle.net/R5bQG /

5
répondu tymeJV 2013-07-18 13:01:46

vous ne devez pas créer des objets jquery pour chaque cellule et rangée. Essayez ceci:

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(""));
}
3
répondu YD1m 2013-07-18 13:04:56
$.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
répondu Iftikhar Khan 2015-08-11 08:08:18

j'ai créé cette fonction 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
répondu M_R_K 2016-11-07 04:42:35

Vous pourriez faire quelque chose comme ceci:

<!-- 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>
1
répondu Kunal Mukherjee 2017-08-15 12:56:03

jQuery.html prend la chaîne de caractères ou le rappel comme entrée, pas sûr de la façon dont votre exemple fonctionne... Essayez quelque chose comme $('<tr>').append($('<td>' + item.rank + '</td>').append ... Et vous avez des problèmes avec les étiquettes. Il devrait être $('<tr/>') et $('<td/>')

0
répondu duskpoet 2013-07-18 13:05:20

je ne suivant pour obtenir de réponse JSON de l'Ajax et de l'analyser sans l'aide de parseJson:

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

si vous utilisez dataType comme texte, alors vous avez besoin de $.parseJSON (réponse)

0
répondu Harpreet 2017-10-04 08:47:27

Données JSON :

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

Vous pouvez utiliser jQuery pour effectuer une itération sur JSON et de créer des tableaux dynamiquement:

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

Voici la fonction size_of_array:

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

vous pouvez aussi ajouter style si nécessaire:

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

résultat :

enter image description here

bien sûr, vous pouvez utiliser une bibliothèque qui fait ces choses pour vous. Par exemple, dans Kedion vous ajoutez simplement JSON à la fonction add_visual:

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

ou vous pouvez simplement saisir le JSON de votre URL et l'utiliser avec votre bibliothèque de choix:

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

enter image description here

0
répondu Cybernetic 2018-05-02 16:55:34