jQuery 在 HTML 表格中显示 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19901843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:47:16  来源:igfitidea点击:

Display JSON Data in HTML Table

jqueryspring-mvc

提问by Abhishek Singh

I get the following JSON String from server as response

我从服务器获得以下 JSON 字符串作为响应

[{"city":"AMBALA","cStatus":"Y"},{"city":"ASANKHURD","cStatus":"Y"},{"city":"ASSANDH","cStatus":"Y"}]

Here is my Jquery Code

这是我的 Jquery 代码

$('#search').click(function() {
    alert("submit handler has fired");
    $.ajax({
        type: 'POST',
        url: 'cityResults.htm',
        data: $('#cityDetails').serialize(),
        success: function(data){ 
            alert(data);    
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;//suppress natural form submission
});

The alert shows the JSON String Correctly. Now i want to map this response to my table

警报正确显示 JSON 字符串。现在我想将此响应映射到我的表

say

How can i do that ??

我怎样才能做到这一点 ??

回答by Hiral

Try this:

尝试这个:

CSS:

CSS:

.hidden{display:none;}

HTML:

HTML:

<table id="table" class="hidden">
    <tr>
        <th>City</th>
        <th>Status</th>
    </tr>
</table>

JS:

JS:

$('#search').click(function() {
    $.ajax({
        type: 'POST',
        url: 'cityResults.htm',
        data: $('#cityDetails').serialize(),
        dataType:"json", //to parse string into JSON object,
        success: function(data){ 
            if(data){
                var len = data.length;
                var txt = "";
                if(len > 0){
                    for(var i=0;i<len;i++){
                        if(data[i].city && data[i].cStatus){
                            txt += "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
                        }
                    }
                    if(txt != ""){
                        $("#table").append(txt).removeClass("hidden");
                    }
                }
            }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;//suppress natural form submission
});

回答by Adween

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.

作为您已有答案的替代方案,以及针对本文中其他人的答案。我最近有一个类似的任务,并创建了一个小的 jquery 插件来为我做这件事。它在缩小后的 3KB 以下非常小,并且具有排序、分页以及显示和隐藏列的能力。

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

使用 css 进行自定义应该很容易。可以在此处找到更多信息http://mrjsontable.azurewebsites.net/,您可以在 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

然后在 ajax 成功方法中你会想要这样的东西

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!

希望它可以帮助别人!

回答by Miquel Las Heras

There are many plugins for doing that. I normally use datatables it works great. http://datatables.net/

有很多插件可以做到这一点。我通常使用数据表,它工作得很好。http://datatables.net/

回答by Gabriel Sadaka

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

循环遍历数据并将其附加到表中,如上面的代码。

回答by Arie

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

我创建了以下函数来从任意 JSON 对象生成 html 表:

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

回答by Kira

Try this:

尝试这个:

  <!DOCTYPE html>
    <html>
    <head>
        <title>Convert JSON Data to HTML Table</title>
        <style>
            th, td, p, input {
                font:14px Verdana;
            }
            tr{
                align: right
            }
            table, th, td 
            {
                border: solid 1px #DDD;
                border-collapse: collapse;
                padding: 2px 3px;
                text-align: center;
            }
            th {
                font-weight:bold;
            }
        </style>
    </head>
    <body>
        <input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
        <div id="showData"></div>
    </body>

    <script>
        function CreateTableFromJSON() {
            var obj = {[{"city":"AMBALA","cStatus":"Y"}, 
                      {"city":"ASANKHURD","cStatus":"Y"}, 
                      {"city":"ASSANDH","cStatus":"Y"}]}

    var table = document.createElement('table');

    var tr = table.insertRow(-1);

    function iterate(obj,table,tr){

        for(var props in obj){

            if(obj.hasOwnProperty(props)){

                if(typeof obj[props]=='object')
                    {
                        var trNext = table.insertRow(-1);
                        var tabCellHead = trNext.insertCell(-1);
                        var tabCell = trNext.insertCell(-1);
                        var table_in = document.createElement('table'); 
                        var tr_in;
                        var th = document.createElement("th");      
                        th.innerHTML = props;

                        tabCellHead.appendChild(th);
                        tabCell.appendChild(table_in)
                        iterate(obj[props],table_in,tr_in);
                    }
                else
                    {
                        if(tr === undefined)
                        {
                            tr = table.insertRow(-1);
                        }
                        var tabCell = tr.insertCell(-1);
                        console.log(props+' * '+obj[props]);
                        tabCell.innerHTML = obj[props];
                    }

            }
        }
    }

    iterate(obj,table,tr);

    var divContainer = document.getElementById("showData");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);

    }
    </script>
    </html>

回答by cybergears

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

回答by Maclane

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.

如果您想从 json 对象获取结果,请使用数据表。Datatable 也以相同的方式将 json 结果转换为表格格式,并具有可搜索和可排序的列的功能。

回答by Anurag

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

检查下面的链接,以最简单和最快的方式将 JSON 数据转换为标准 HTML 表。

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

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