Convert JSON array to an HTML table in jQuery

前端 未结 15 1089
温柔的废话
温柔的废话 2020-11-22 16:33

Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?

15条回答
  •  没有蜡笔的小新
    2020-11-22 17:06

    Pure HTML way, not vulnerable like the others AFAIK:

    // Function to create a table as a child of el.
    // data must be an array of arrays (outer array is rows).
    function tableCreate(el, data)
    {
        var tbl  = document.createElement("table");
        tbl.style.width  = "70%";
    
        for (var i = 0; i < data.length; ++i)
        {
            var tr = tbl.insertRow();
            for(var j = 0; j < data[i].length; ++j)
            {
                var td = tr.insertCell();
                td.appendChild(document.createTextNode(data[i][j].toString()));
            }
        }
        el.appendChild(tbl);
    }
    

    Example usage:

    $.post("/whatever", { somedata: "test" }, null, "json")
    .done(function(data) {
        rows = [];
        for (var i = 0; i < data.Results.length; ++i)
        {
            cells = [];
            cells.push(data.Results[i].A);
            cells.push(data.Results[i].B);
            rows.push(cells);
        }
        tableCreate($("#results")[0], rows);
    });
    

提交回复
热议问题