JSON到HTML表使用' datatable'插入

时间:2016-02-24 07:56:58

标签: javascript jquery json jquery-plugins datatables

我试图从SQL查询执行的结果生成HTML数据表。结果数据采用JSON格式。我正在使用插件" Datatables"为达到这个。我跟着这个example

我没有收到错误,但数据表为空。我显然做错了什么或遗失了什么。

这是代码摘录。我可以请一些正确的道路指导。

def list_subdirs(in_path):
    subdirs = []
    for x in os.walk(in_path):
        subdirs.append(x[0])
    return subdirs

JSON结果

function jsDataPlot(chartProps) {
    // Get the array from the element:
    var graphPropsStore = chartProps;

    // Loop through the array with the jQuery each function:
    $.each(graphPropsStore, function (k, graphPropsStoreProperty) {

        // The makeCall function returns a ajaxObject so the object gets put in var promise
        var dbResAjx = getResultFromSql(k);

        // Now fill the success function in this ajaxObject (could also use .error() or .done() )
        dbResAjx.success(function (response) {
            console.log(response);
            // When success, call the function and use the values out of the array above
            $('#divId').DataTable(response);
        });

        dbResAjx.error(function (response) {
            console.log(response);
        });
    });
}


    function getResultFromSql(paramId) {
// bla bla code
        return $.ajax({
            url: 'runMySqlQuery.php',
            type: 'post',
            data: {// some POST params}
        });
    }

1 个答案:

答案 0 :(得分:1)

好的,在你的JSON中你有这个。日期 - 类型 - 姓名

 [
    {"DATE":"2015-12-15","TYPE":"AAA","NAME":"asdasd"},
    {"DATE":"2015-12-15","TYPE":"BBB","NAME":"dsfsdfsdfsdf"},
    {"DATE":"2015-12-15","TYPE":"AAA","NAME":"reterter"},
    {"DATE":"2015-12-15","TYPE":"CCC","NAME":"ertertertert"}
 ]

然后在你的JS中应该定义你的列......

$('#divId').DataTable({
  columns : [
      {data: "DATE"},
      {data: "TYPE"},
      {data: "NAME"}
  ],
    data: response
});

示例:https://jsfiddle.net/cmedina/7kfmyw6x/4/