복붙노트

[JQUERY] AJAX 응답에서 빌드 테이블 행에 사용 jQuery를 (JSON)

JQUERY

AJAX 응답에서 빌드 테이블 행에 사용 jQuery를 (JSON)

해결법


  1. 1.사용 .html 중에서 대신으로 .Append

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

  2. 2.이 (DEMO 링크 업데이트)를보십시오 :

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

    바이올린 DEMO 함께 AJAX


  3. 3.여기 hmkcode.com에서 완전한 대답은

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

  4. 4.이런 식으로 시도 :

    이런 식으로 시도 :

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


  5. 5.당신은 각 셀 및 행에 대한 객체를 JQuery와 생성해서는 안된다. 이 시도:

    당신은 각 셀 및 행에 대한 객체를 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. 6.

    $.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. 7.JSON으로 데이터 :

    JSON으로 데이터 :

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

    동적으로 테이블을 JSON 반복하고 만들 jQuery를 사용할 수 있습니다 :

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

    결과:


  8. 8.나는이 JQuery와 기능을 만들었습니다

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

  9. 9.당신은이 같은 뭔가를 할 수 :

    당신은이 같은 뭔가를 할 수 :

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

  10. 10.귀하의 예제가 작동하는 방법 jQuery.html는 확실하지, 입력으로 문자열이나 콜백을 걸립니다 ... 시도 $ 같은 것을 ( ''). APPEND ($ ( ''+ item.rank + ' '). APPEND ... 그리고 당신은 태그 fromation 몇 가지 분명한 문제가있다. 그것은 $해야한다 ( '')와 $ ( '')

    귀하의 예제가 작동하는 방법 jQuery.html는 확실하지, 입력으로 문자열이나 콜백을 걸립니다 ... 시도 $ 같은 것을 ( ''). APPEND ($ ( ''+ item.rank + ' '). APPEND ... 그리고 당신은 태그 fromation 몇 가지 분명한 문제가있다. 그것은 $해야한다 ( '')와 $ ( '')


  11. 11.나는 parseJson를 사용하지 않고 JSON 아약스에서 응답 및 구문 분석을 얻기 위해 다음을 수행 :

    나는 parseJson를 사용하지 않고 JSON 아약스에서 응답 및 구문 분석을 얻기 위해 다음을 수행 :

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

    당신은 텍스트로 데이터 유형을 사용하는 경우에 당신은 .parseJSON (응답) $ 필요


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

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

    함수 fetchAllReceipts (documentShareId) { 을 console.log ( 'HTTP 호출 :'+ URI + "/"+ documentShareId) {(아약스 $ URL : URI + "/"+ documentShareId, 입력 : "GET", ContentType을 : "응용 프로그램 / JSON;" 캐시 : 거짓, 성공 : 기능 (영수증) { //console.log(receipts); $ (영수증) .each (기능 (인덱스 항목) { CONSOLE.LOG (항목); //console.log(receipts[index]); $ ( '# 영수증 TBODY'). APPEND ( ' '+ item.Firstname + ','+ + item.Lastname ' '+ + item.TransactionId ' '+ + item.Amount ' '+ + item.Status ' ' ) }); }, 오류 : 함수 (XMLHttpRequest 객체, textStatus, errorThrown) { CONSOLE.LOG (XMLHttpRequest 객체); CONSOLE.LOG (textStatus); CONSOLE.LOG (errorThrown); } }); } // 샘플 JSON 데이터는 서버에서 오는 VAR 데이터 = 0 "d99803ce-31d9-48a4-9d70-f99bf927a208", 이름 : {ID : "7a4c411e-9a84-45eb-9c1b-2ec502697a4d"DocumentId : DocumentShareId "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6" "Test1을" , 성 : "Test1을",} 1 '- d99803ce 31d9-48a4-9d70-f99bf927a208 ", 이름 :"시험 2 {ID : "7a4c411e-9a84-45eb-9c1b-2ec502697a4d"DocumentId : DocumentShareId "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6" "성"Test2를 ",} ]; <버튼형 = "버튼"클래스 = "BTN BTN - 우선"의 onclick = "fetchAllReceipts ("@ share.Id ") '> 영수증

    <표 클래스 = "테이블 테이블 호버"> <제> 이름 <제> 트랜잭션 <제> 개수 <제> 상태

  13. from https://stackoverflow.com/questions/17724017/using-jquery-to-build-table-rows-from-ajax-responsejson by cc-by-sa and MIT license