简体   繁体   中英

Passing dynamic JSON data to create a HTML table

I have a function that receives JSON data, it can be any length and contain any number of columns and rows of data.

I have read that jqGrid would be a good jQuery plugin to use for this scenario but I cannot get it to work.

I have the following code to try and get my table to be populated:

//This code is in another section of my web page but the data is valid 
//and is populated over a websocket
var ss = $.parseJSON(data);
var theGrid = jQuery("#list1")[0];
theGrid.addJSONData(ss.NewDataSet.SECURITY_GROUPS);
//alert(ss.NewDataSet.SECURITY_GROUPS[0].NAME);

$(document).ready(function() {
           jQuery("#list1").jqGrid({
            datatype: "local",
            height: 250,
            multiselect: true,
            caption: "Manipulating Array Data"
        });
         });

<table id="list1"></table>

Maybe give DataTables a try if jqGrid isn't working for you. It's probably my favorite, and super easy to load via JSON as you've described.

Here's how to load from an AJAX source: http://datatables.net/release-datatables/examples/data_sources/ajax.html

$(document).ready(function() {
    $('#example').dataTable( {
        "bProcessing": true,
        "sAjaxSource": '../ajax/sources/arrays.txt'
    });
});

UPDATE

var columnArr = [];
var valueArr = [];
var data = ss.NewDataSet.SECURITY_GROUPS; //data is your SECURITY_GROUPS object

//Strip the titles off your first array item only since they are all the same.
$.each(data[0], function(key, value) {
    columnArr.push({"sTitle" : key});
});

$.each(data, function(key, value) {
    var innerArr = [];
    $.each(value, function(innerKey, innerValue) {
        innerArr.push(innerValue);
    });
    valueArr.push(innerArr);
});

$('#example').dataTable( {
    "aaData": valueArr,
    "aoColumns": columnArr
});    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM