javascript - 使用 'datatable' 插件将 JSON 转换为 HTML 表

标签 javascript jquery json jquery-plugins datatables

我正在尝试根据 SQL 查询执行的结果生成 HTML 数据表。生成的数据为 JSON 格式。我正在使用插件“Datatables”来实现此目的。我正在关注这个example

我没有收到错误,但数据表为空。我显然做错了什么或遗漏了一些东西。

这是代码摘录。我能否获得一些关于正确路径的指导。

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

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

最佳答案

好的,在你的 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/

关于javascript - 使用 'datatable' 插件将 JSON 转换为 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35596325/

相关文章:

python - JSON 架构 : Validate that exactly one property is present

Javascript token 替换/追加

javascript - 使 textarea 高度扩展到容器 div 的高度(调整大小时)

Python ISO 日期时间包含 'T' 字符

javascript - 如何将元素的 id 传递给 .js 文件?

jquery - 每列中第一个 td 不为空的 CSS 选择器

javascript - 选择哪种格式在 D3.js 中动态存储和显示数据?

javascript - 需要正则表达式来验证时间格式

javascript - 当所有屏幕通过 React Navigation 获得焦点时,在每个屏幕上执行相同的功能

javascript - 使用 .stop() 后悬停卡住时的 jQuery fadeIn 和 fadeOut