Convert JSON array to an HTML table in jQuery

前端 未结 15 1090
温柔的废话
温柔的废话 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 16:43

    Converting a 2D JavaScript array to an HTML table

    To turn a 2D JavaScript array into an HTML table, you really need but a little bit of code :

    function arrayToTable(tableData) {
        var table = $('
    '); $(tableData).each(function (i, rowData) { var row = $(''); $(rowData).each(function (j, cellData) { row.append($(''+cellData+'')); }); table.append(row); }); return table; } $('body').append(arrayToTable([ ["John","Slegers",34], ["Tom","Stevens",25], ["An","Davies",28], ["Miet","Hansen",42], ["Eli","Morris",18] ]));


    Loading a JSON file

    If you want to load your 2D array from a JSON file, you'll also need a little bit of Ajax code :

    $.ajax({
        type: "GET",
        url: "data.json",
        dataType: 'json',
        success: function (data) {
            $('body').append(arrayToTable(data));
        }
    });
    

提交回复
热议问题