programing

jQuery를 사용하여 AJAX 응답 (json)에서 테이블 행 작성

nasanasas 2020. 10. 31. 09:47
반응형

jQuery를 사용하여 AJAX 응답 (json)에서 테이블 행 작성


중복 가능한 중첩 요소

서버 측 ajax response (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이있는 행 하나만 얻습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?


.html 대신 .append 사용

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

이것을 시도하십시오 (데모 링크 업데이트 됨) :

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를 사용한 바이올린 데모


다음은 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)
    ); 
});  

다음과 같이 시도하십시오.

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


각 셀과 행에 대해 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(""));
}

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

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

결과 :

여기에 이미지 설명 입력

또는 AZLE 사용

Azle 에서는 JSON 데이터를 추가하여 다음과 같이 테이블을 생성하기 만하면됩니다.

보류 div가 있는 섹션추가합니다 .

az.add_sections({
    "this_class": "my_sections",
    "sections": 1
})
az.add_html('my_sections', 1, {
    "html": "<div class='holdng_div'></div>"
})

여기에 이미지 설명 입력

테이블을 그리는 래핑 된 함수를 만듭니다. 여기 에서는 일부 루핑 및 스타일링과 함께 Azle의 add_layoutfill_row 함수를 사용합니다.

az.add_wrapped_function({
        "name": "draw_table",
        "function": function draw_table(data) {
            az.add_layout('holdng_div', 1, {
                "this_class": "my_table",
                "row_class": "my_table_rows",
                "cell_class": "my_table_cells",
                "number_of_rows": data.length,
                "number_of_columns": 5
            })
            data_ = data
            az.fill_row('my_table', 1, {
                "header": false,
                "cell_class": "my_table_cells",
                "text_class": "header_text",
                "row_number": 1,
                "array": Object.keys(data[0])
            })
            az.all_style_text('header_text', {
                "color": "yellow",
                "font-family": "Arial"
            })
            az.call_multiple({
                "iterations": data.length,
                "function": `
                    az.fill_row('my_table', 1, {
                        "header": true,
                        "cell_class": "my_table_cells",
                        "row_number": index + 1,
                        "array": [data_[index]['sepalLength'],data_[index]['sepalWidth'],data_[index]['petalLength'],data_[index]['petalWidth'],data_[index]['species']]
                        })
                        `
            })
            az.alternate_row_color('my_table', 1, 'whitesmoke', '#33AADE', 'black', 'black', true)
        }
    })

마지막으로 데이터를 반환하는 API를 호출하고 (여기서는 Github에서 호스팅되는 Iris 데이터 세트를 사용합니다) 해당 데이터를 래핑 된 함수에 전달합니다.

az.call_api({
        "url": "https://raw.githubusercontent.com/domoritz/maps/master/data/iris.json",
        "parameters": {},
        "done": "az.call_wrapped_function.draw_table(data)"
    })

결과 :

여기에 이미지 설명 입력

다음은 GIST입니다.

여기 FIDDLE입니다


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

다음과 같이 할 수 있습니다.

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

jQuery.html은 문자열 또는 콜백을 입력으로 사용합니다. 예제가 어떻게 작동하는지 확실하지 않습니다. 다음과 같이 시도해보십시오 $('<tr>').append($('<td>' + item.rank + '</td>').append .... 태그 생성에 확실한 문제가 있습니다. 그것은이어야 $('<tr/>')하고$('<td/>')


Ajax에서 JSON 응답을 받고 parseJson을 사용하지 않고 구문 분석하려면 다음을 수행합니다.

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

dataType을 Text로 사용하는 경우 $ .parseJSON (response)이 필요합니다.


이것은 내 프로젝트에서 복사 한 작업 샘플입니다.

 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>
         
 
    
    
    

참고 URL : https://stackoverflow.com/questions/17724017/using-jquery-to-build-table-rows-from-ajax-responsejson

반응형