Display JSON Data in HTML Table

后端 未结 9 2037
既然无缘
既然无缘 2020-11-27 03:47

I get the following JSON String from server as response

[{\"city\":\"AMBALA\",\"cStatus\":\"Y\"},{\"city\":\"ASANKHURD\",\"cStatus\":\"Y\"},{\"city\":\"ASSA         


        
相关标签:
9条回答
  • 2020-11-27 04:20

    check below link to convert JSON data to standard HTML table in the simplest and fastest way.

    http://crunchify.com/crunchifyjsontohtml-js-json-to-html-table-converter-script/

    0 讨论(0)
  • 2020-11-27 04:22
    HTML:
     <div id="container"></div>   
    JS:
    
    
    $('#search').click(function() {
        $.ajax({
            type: 'POST',
            url: 'cityResults.htm',
            data: $('#cityDetails').serialize(),
            dataType:"json", //to parse string into JSON object,
            success: function(data){ 
    
                    var len = data.length;
                    var txt = "";
                    if(len > 0){
                        for(var i=0;i<len;i++){
    
                                txt = "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
                                $("#container").append(txt);
                        }
    
    
    
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert('error: ' + textStatus + ': ' + errorThrown);
            }
        });
        return false;
    });
    
    0 讨论(0)
  • 2020-11-27 04:26

    I created the following function to generate an html table from an arbitrary JSON object:

    function toTable(json, colKeyClassMap, rowKeyClassMap){
        let tab;
        if(typeof colKeyClassMap === 'undefined'){
            colKeyClassMap = {};
        }
        if(typeof rowKeyClassMap === 'undefined'){
            rowKeyClassMap = {};
        }
    
        const newTable = '<table class="table table-bordered table-condensed table-striped" />';
        if($.isArray(json)){
            if(json.length === 0){
                return '[]'
            } else {
                const first = json[0];
                if($.isPlainObject(first)){
                    tab = $(newTable);
                    const row = $('<tr />');
                    tab.append(row);
                    $.each( first, function( key, value ) {
                        row.append($('<th />').addClass(colKeyClassMap[key]).text(key))
                    });
    
                    $.each( json, function( key, value ) {
                        const row = $('<tr />');
                        $.each( value, function( key, value ) {
                            row.append($('<td />').addClass(colKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap)))
                        });
                        tab.append(row);
                    });
    
                    return tab;
                } else if ($.isArray(first)) {
                    tab = $(newTable);
    
                    $.each( json, function( key, value ) {
                        const tr = $('<tr />');
                        const td = $('<td />');
                        tr.append(td);
                        $.each( value, function( key, value ) {
                            td.append(toTable(value, colKeyClassMap, rowKeyClassMap));
                        });
                        tab.append(tr);
                    });
    
                    return tab;
                } else {
                    return json.join(", ");
                }
            }
    
        } else if($.isPlainObject(json)){
            tab = $(newTable);
            $.each( json, function( key, value ) {
                tab.append(
                    $('<tr />')
                        .append($('<th style="width: 20%;"/>').addClass(rowKeyClassMap[key]).text(key))
                        .append($('<td />').addClass(rowKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap))));
            });
            return tab;
        } else if (typeof json === 'string') {
            if(json.slice(0, 4) === 'http'){
                return '<a target="_blank" href="'+json+'">'+json+'</a>';
            }
            return json;
        } else {
            return ''+json;
        }
    };
    

    So you can simply call:

    $('#mydiv').html(toTable([{"city":"AMBALA","cStatus":"Y"},{"city":"ASANKHURD","cStatus":"Y"},{"city":"ASSANDH","cStatus":"Y"}]));
    
    0 讨论(0)
  • 2020-11-27 04:27

    Please use datatable if you want to get result from json object. Datatable also works in the same manner of converting the json result into table format with the facility of searchable and sortable columns automatically.

    0 讨论(0)
  • 2020-11-27 04:33
              <table id="myData">
    
              </table>
    
               <script type="text/javascript">
                  $('#search').click(function() {
                        alert("submit handler has fired");
                        $.ajax({
                            type: 'POST',
                            url: 'cityResults.htm',
                            data: $('#cityDetails').serialize(),
    
                            success: function(data){ 
                                $.each(data, function( index, value ) {
                                   var row = $("<tr><td>" + value.city + "</td><td>" + value.cStatus + "</td></tr>");
                                   $("#myData").append(row);
                                });
                            },
                            error: function(jqXHR, textStatus, errorThrown){
                                alert('error: ' + textStatus + ': ' + errorThrown);
                            }
                        });
                        return false;//suppress natural form submission
                    }); 
    
       </script>
    

    loop through the data and append it to a table like the code above.

    0 讨论(0)
  • 2020-11-27 04:36

    As an alternative to the answers you already have, and for others that come accross this post. I recently had a similar task and created a small jquery plug in to do it for me. Its pretty small under 3KB minified, and has sorting, paging and the ability to show and hide columns.

    It should be pretty easy to customize using css. More information can be found here http://mrjsontable.azurewebsites.net/ and the project is available for you to do as you wish with on github https://github.com/MatchingRadar/Mr.JsonTable

    To get it to work download the files and pop them in your site. Follow the instructions and you should end up with something like the following:

    <div id="citytable"></div>
    

    Then in the ajax success method you will want something like this

    success: function(data){ 
        $("#citytable").mrjsontable({
            tableClass: "my-table",
            pageSize: 10, //you can change the page size here
            columns: [
                new $.fn.mrjsontablecolumn({
                    heading: "City",
                    data: "city"
                }),
                new $.fn.mrjsontablecolumn({
                    heading: "City Status",
                    data: "cStatus"
                })
            ],
            data: data
        });
    }
    

    Hope it helps somebody else!

    0 讨论(0)
提交回复
热议问题