首页 > 解决方案 > DataTables 表未填充

问题描述

我有一个应用程序,我在其中执行存储在数据库中的查询。每个都可能针对不同的表,其中检索到的列集不同。类似于执行临时查询的应用程序。

所以我有以下 JavaScript 代码:

function populateSummaryReport() {

if ($('#summaryTable').length) {
    $('#sumaryTable').remove;
}


const getReport = {
    jobID: $('#jobID').val(),
    beginDate: $('#summaryStart').val(),
    endDate: $('#summaryEnd').val(),
    tableType: 'Summary'};

$.ajax({
    url: "php/reports.php",
    contentType: "application/json",
    type: "post",
    dataType: "json",
    data: JSON.stringify(getReport)
}).done(function (response, textStatus, jqXHR) {
    //success

    if (response["tableColumns"][0].substring(0, 4) === "<h4>") { //if html returned here no detail query
        $('summaryReportPlaceholder').html(response);
    } else {

//build table
        var tableDef =
                "<table id='summaryTable' class='display' width='100%'>" +
                "<caption>" + $('#jobID').val() + " Summary Report</caption>" +
                "<thead><tr>";
        //build thead 
        for (const colName of response["tableColumns"]) {
            tableDef += "<th>" + colName + "</th>";
            
        }
        
        tableDef += "</tr></thead></table>";
        
        $('#summaryReportPlaceholder').html(tableDef);
        $('#summaryTable').DataTable({

            select: {
                sytle: 'single',
                items: 'row'
            },
            data: response["tableData"],
            //
            //columns: response["tableColumns"],
            dataSrc: "",
            paging: false,
            scrollY: '60vh',
            scrollCollapse: true,
            order: []
        });
    }
}).fail(function (jqHXR, textStatus, errorThrown) {
    alert("error " + textStatus + "  " + jqHXR + " " + errorThrown);
}).always(function (jqxHRorData, textStatus, jqXHROrErrorThrown) {
    alert("complete");
});

}

此代码被执行(从另一个函数调用);reports.php 返回预期的 json 并且代码属于 .done 函数。我期待#summaryTable 被填充,但事实并非如此。我确实得到了一个具有适当行数的表,但数据都是空白的。

我将以下帖子作为我的灵感:bindrid / datatables forums

注意:自从我的原始帖子以来,我将表的构建移动到 ajax 调用的 .done 部分,并添加了列名。我现在收到以下警告(两次)DataTables 警告:table id=summaryTable - Requested unknown parameter '0' for row 0, column 0。有关此错误的更多信息,请参阅http://datatables.net/tn/4

我确实查找了上面的 url,但是我没有看到我的数据适合所描述的任何场景。其中一些对我来说是希腊语,所以我可能会遗漏一些东西。

标签: javascriptphpdatatables

解决方案


当 DataTables 应用

data: response["tableData"]

它将 response["tableData"] 视为数字索引数组,因为列映射未在 columns 选项中定义。

reports.php 返回的是一个关联数组:

oci_fetch_array($tableQuery, OCI_ASSOC + OCI_RETURN_NULLS)

将reports.php 中的代码更改为:

oci_fetch_array($tableQuery, OCI_NUM + OCI_RETURN_NULLS)

解决了我的问题。


推荐阅读