完全动态的DataTable PHP

时间:2016-02-11 16:38:09

标签: php json datatable

我正在尝试在模态中创建一个完全动态的数据表开口。起初它给了我正确的结果,但是当我打开一个新的模态时,它给了我这个错误:

  

DataTables警告:table id = tableDetails - 无法重新初始化DataTable。有关此错误的详细信息,请参阅http://datatables.net/tn/3

希望你能提供帮助。谢谢。

这是我正在使用的代码: [模态]:

<div id="myModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="modalTitle"></h4>
        </div>

        <div class="modal-body">
            <table class="table table-hover table-bordered" id="tableDetails"></table>
        </div>
    </div>
</div>

[数据表]

$.getJSON( "controller/kpi.php", {
    abrArq: abreviatesArq,
    idKpi: idKpi
}, function(detailsKpi){        

    var detailsHeader = "";
    var detailsBody = "";

    //Validar 'thead' 
    if(detailsKpi["tableH"])
    {
        $("#tableDetails").append('<thead id="detailsHeader"></thead>');
    }


    $("#tableDetails").append('<tbody id="detailsBody"></tbody>');


    //Validar 'tbody'
    if(detailsKpi["tableB"])
    {   
        $("#tableDetails").append('<tbody id="detailsBody"></tbody>');

        //Header Tabela
        detailsHeader += "<tr>";
            $.each(detailsKpi["tableH"], function(dkHind, dkHobj){
                var string = dkHobj.toUpperCase();

                detailsHeader += "<th>";
                    detailsHeader += string;
                detailsHeader += "</th>";
            });
        detailsHeader += "</tr>";


        //Body Tabela
        $.each(detailsKpi["tableB"], function(dkBind, dkBobj)
        {
            detailsBody += '<tr>';
                $.each(detailsKpi["tableH"], function(dkHindex, dkHobjecto)
                {
                    detailsBody += '<td>';
                        detailsBody += dkBobj[dkHobjecto];
                    detailsBody += '</td>';
                });
            detailsBody += '</tr>';
        });
    }
    //Se não existerem resultados apresenta mensagem
    //'Não foram encontrados resultados'
    else
    {
        detailsBody = "<div class='noResults'>Não foram encontrados resultados</div>";
        $("#tableDetails").removeClass("table-bordered");
    }


    //Anexar Informação na tabela
    $("#detailsHeader").append(detailsHeader);
    $("#detailsBody").append(detailsBody);


    //Chamar DataTable
    $('#tableDetails').DataTable({
        //Número de registos a mostrar por página
        "aLengthMenu": [
            [10, 50, -1],
            [10, 50, "Tudo"]
        ],
        //Textos usados nas datatables
        "oLanguage": {
            "sSearch": "Pesquisar:",
            "sLengthMenu": "Mostra _MENU_ por página",
            "sInfoEmpty": "Nenhum registro encontrado",
            "sInfo": "Total de _TOTAL_ registos para mostrar (_START_ a _END_)",
            "sEmptyTable": "Sem dados disponíveis na tabela",
            "sInfoFiltered": " - filtrado de _MAX_ registos",
            "sZeroRecords": "Não foram encontrados nenhuns registos",
            "oPaginate": {
                "sFirst": "Primeira Página",
                "sLast": "Última Página",
                "sNext": "Seguinte",
                "sPrevious": "Anterior"
            }
        },
    });
});


//Limpar Modal #1
$("#detailsHeader").text("");
$("#detailsBody").text("");

[查询]

$this->cleanErrors();
        $this->sql->cleanErrors();

        $table = $param["abrArq"].'_kpi'.$param["idKpi"].'_detail';


        //SELECT COLUMNS
        $columns = "SHOW COLUMNS FROM " . $table;
        $this->sql->query($columns);

        $detCol = array();
        while($cRow = $this->sql->fetchRow())
        {
            $detCol[] = $table.'.'.$cRow["Field"];
        };
        $listCol = implode(", ", $detCol);


        //SELECT RESULTS
        $query="SELECT ".
                    $listCol."
                FROM ".
                    $table;
        $this->sql->query($query);


        //echo $query;


        if($this->sql->hasErrors())
        {
            $this->errors = $this->errors + $this->sql->errors;
            return false;
        }

        while($row = $this->sql->fetchRow())
        {
            $res[] = $row;
        }

        if($this->sql->hasErrors())
        {
            $this->errors = $this->errors + $this->sql->errors;
            return false;
        }

        return $res;

2 个答案:

答案 0 :(得分:0)

在首页中仅包含一次datatable js。 删除初始化主页中数据表的每个js代码。 在脚本标签的页脚后添加js代码以进行模式初始化。

如果这样做不起作用,请尝试在模式开始关闭时在js上添加数据表销毁。

我希望我很清楚。

答案 1 :(得分:0)

这是一个非常常见的问题,您可以避免(...)深入阅读Datatable文档。我一次又一次地经历了同样的问题。

最后,在创建我的表之前,您已解决了销毁任何数据表初始化的问题,您需要添加:

 if ( $.fn.DataTable.isDataTable('#myAwesomeTable') ) {
  $('#myAwesomeTable').DataTable().destroy();
}

初始化前的距离

 if ( $.fn.DataTable.isDataTable('#myAwesomeTable') ) {
      $('#myAwesomeTable').DataTable().destroy();
    }




        $('#myAwesomeTable').DataTable({
            "responsive": true,
            "processing" : true,
            "ajax" : {
                "url" : "...",
                dataSrc : ''
            },
            "columns" : [
            {
                "data" : "id"
            }, {
                "data" : "name"
            }]
        }).draw(true).columns.adjust();
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
              console.log("Status: " + textStatus); alert("Error: " + errorThrown);
      }
    });
});

在Url中,您可以使用一个php文件,该文件将具有一个简单的PDO PHP MYSQL调用,并且可以回显一个像这样的json_encode函数:

<?php

require "../../../class/PDO.class.php";
require "../../../class/helper.class.php";

$new = $_POST['id'];
$mundialorder = $_POST['irOrder'];

//var_dump($_POST);

 $valores = array(
      $new,
      $mundialorder
      );

 $DB = new Db(DBHost, DBName, DBUser, DBPassword);

    $sql = "UPDATE me SET please= ? WHERE person = ?";


    if($DB->query($sql,$valores) > 0)  {

            //$usuario = Helper::obtain_my_simple_JSON();

             $msg = "S";





        $data['success'] = true;
        $data['message'] = "good";

    }else{
        $data['success'] = false;
        $data['errors'] = "Error";
    }



echo json_encode($data);

?>