带有数据表和 AJAX 的动态表

Posted

技术标签:

【中文标题】带有数据表和 AJAX 的动态表【英文标题】:Dynamic table with Datatables and AJAX 【发布时间】:2021-09-04 23:52:24 【问题描述】:

我正在创建一个类来根据传递给它的参数生成 CRUD 表。

我不知道如何在"ajax":"columns": 请求中正确传递我的数据,以便为我创建表。

我正在使用以下 4 个文件:

1.- main.php:此文件包含我的课程GenerateCrud

<?php
        
    class GenerateCrud 
        
        // Properties.
        
            public $tableName;
            public $id;
            public $tableFields = array();
    
        // Constructor.
        
            function __construct($tableName, $id, $tableFields)
                $this->tableName = $tableName;
                $this->id = $id;
                $this->tableFields = $tableFields;
            
            
            public function create()               
                if(empty($_SESSION['Cookie']))
                    $strCookie = tempnam("/tmp", "COOKIE");
                    $_SESSION['Cookie'] = $strCookie;
                else
                    $strCookie = $_SESSION['Cookie'];
                
                
                // Creating the session.
                $curl_handle = curl_init (SITE_URL.'/admin/login.php');
                curl_setopt ($curl_handle, CURLOPT_COOKIEJAR, $strCookie);
                curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
                $vars= 'user=cron&pass='.CRON_PASS.'&action='.md5('login');
                curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $vars);
                $output = curl_exec ($curl_handle);

                // Loging in.           
                curl_setopt ($curl_handle, CURLOPT_URL, SITE_URL_ADMIN.'/alexcrudgenerator/crud/res/');
                curl_setopt ($curl_handle, CURLOPT_COOKIEJAR, $strCookie);
                curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
                $vars= 'action=showtable&tableName='.$this->tableName.'&id='.$this->id.'&tableFields='.json_encode($this->tableFields);
                curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $vars);               
                $output = curl_exec ($curl_handle);
                
                // I get the result.
                return $output;     
?>
<?php 
            
    
?>

2.- res.php:包含负责构建表的代码。

<?php

    include_once(DIR_PLUGINS.'/alexcrudgenerator/main.php');
    
    $test = new GenerateCrud('users_test', '2', ['usuario', 'apellido1', 'apellido2', 'email']);
    
    switch($_POST['action'])
        
        case 'showtable':
            
            $res = getEntireTable();
            
            // Getting the <TH>.
            $theCol = array();
            foreach ($test->tableFields as $r)
                $theCol[]=array('data'=>$r);
            
            $myHeader = json_encode($theCol);
            echo $myHeader . '<br><br>';

            // Gettint the columns (data of my database).
            $json = array();
            foreach ($res as $data)
                $json['data'][] = $data;            
            
            $myContent = json_encode($json);
            echo $myContent;
                
?>
            <div class="container caja">
                <div class="row">
                    <div class="col-lg-12 col-sm-12">
                        <div>
                            <table id="tablaUsuarios" class="table table-striped table-bordered table-condensed" style="width:100%" >
                                <thead class="text-center">
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <script>
                $(document).ready(function() 
                    var tableName = "<?= $test->tableName; ?>";
                    var id = "<?= $test->id; ?>";
                    var tableFields = "<?= $test->tableFields; ?>";
                    var tableFieldsJson = <?= json_encode($test->tableFields); ?>;
                    var myContent = <?= $myContent ?>;
                    var myHeader = <?= $myHeader ?>;

                    console.log(myContent);

                    $('#crudTable').DataTable(
                        "language": "url": "//cdn.datatables.net/plug-ins/1.10.20/i18n/Spanish.json",
                        "paging": true,
                        "lengthChange": true,
                        "searching": true,
                        "info": true,
                        "autoWidth": true,
                        "scrollX": true,

                        "ajax": 
                            "url": '<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/',
                            "method": "POST",
                            "data": myContent, action: 'showtable'
                        ,
                        "columns": [
                            "data": myHeader,
                            "defaultContent": "<div class='text-center'><div class='btn-group'><button class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>"
                        ]
                    );
                )
            </script>
<?php
        break;      

?>

3.- funciones.php:包含函数(主要是数据库调用)。

<?php

    function getEntireTable()
        global $DB;
        
        $test = new GenerateCrud('users_test', '2', ['usuario', 'apellido1', 'apellido2', 'email']);
        
        $myStringArray = implode(",", $test->tableFields);
            
        $sql = "SELECT $myStringArray FROM $test->tableName";
        $res = $DB->get_records($sql);
        
        return $res;
    

?>

4.- test.php:我将在其中创建最终表格的文件(这是用户将看到的)。

<?php
    
        // Instanced object
    
        $test = new GenerateCrud('users_test', 'id', ['usuario', 'apellido1', 'apellido2', 'email']);
        $res = $test->create();
    
        echo $res;
        
?>

我的问题:我试图将$myHeader$myContent 传递为"data": 来构建我的表,但我做错了什么,我不知道是什么。

(我检查了浏览器的“网络”选项卡中是否发送了任何请求,但没有启动任何请求)。

$myHeader:包含我的表的 TH。 $myContent:包含我的数据库内容。

这里有一张图片可以看得更清楚。

没错,我做错了什么?我以 JSON 格式正确获得了这 2 个变量。

提前致谢,各位,周一愉快!

【问题讨论】:

【参考方案1】:

我认为你错过了 js 和 php 返回数据中的某些内容。

让我们从js开始,通常我在datatable调用中设置这个选项来做一个ajax表:

"processing": true,
"serverSide": true,
"ajax":
   "url" : MyUrl,
   "type": "POST",
    "data": function ( d ) 
        d.somedata = "some data";
    ,
    "error": function()
        $("#table").css("display","none");
        //here you can also display a error message for end user
    ,
,
drawCallback: function() 
   //here you can call whatever function in js need to be restored
   //also buttons function or tooltips or popovers
,

对于php datatable,希望数据以特定格式json返回:

$requestData    =   $_REQUEST;//in this $requestData you will get every parameter from $_POST and $_GET and can be used in elaboration of the data of the table
$query = "myquery";
$row_db = $mysqli->query($query);
$TotalRow = $row_db->num_rows;
//Apply here the filter based on search or whatelse
$row_db = $mysqli->query($query);
$RowFiltered = $row_db->num_rows;
$rowTable = array();
while($row = $row_db->fetch_assoc()) //or fetch_object
   $nestedData = array();
   $nestedData[] = $row["col1"];
   $nestedData[] = $row["col2"];
   //at the end of insert data in nestedData array put this
  $rowTable[] = $nestedData;

当所有数据都准备好打印出数据表时

$json_data = array(
     "draw"            => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
     "recordsTotal"    => intval( $TotalRow ),  // total number of records
     "recordsFiltered" => intval( $RowFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
     "data"            => $rowTable   // total data array
);
print_r(json_encode($json_data));

在最终结果中,从 php 打印出来的“数据”与您显示的 (imge) 数据确实不同。

【讨论】:

以上是关于带有数据表和 AJAX 的动态表的主要内容,如果未能解决你的问题,请参考以下文章

使用 PHP 和 Ajax 创建动态表以将数据插入表中,如果不在视图或第一页中,则无法使用按钮

从ajax侧边栏加载的带有bootstrap-4动态侧边栏菜单的Adminlte 3打开不起作用

AJAX 调用似乎从未发生过

带有表变量的动态查询以循环遍历所有表以在数据库中更新

带有 ASP.NET MVC 和 AJAX 的分页表 [关闭]

Ajax 无法正常工作。 PHP 无法在 SQL 中插入数据