簡體   English   中英

帶有數據表和 AJAX 的動態表

[英]Dynamic table with Datatables and AJAX

我正在創建一個 class 以根據傳遞給它的參數生成 CRUD 表。

我不知道如何在"ajax":"columns":請求中正確傳遞我的數據,以便為我創建表格。

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

1.- main.php :此文件包含我的 class 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;      
}
?>

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 格式正確獲得了這兩個變量。

提前致謝,伙計們,祝你周一愉快!

我認為您在 js 和 php 返回數據中遺漏了一些東西。

讓我們從 js 開始,通常我在數據表調用中設置此選項以執行 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 數據表,希望數據以特定格式返回 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)數據確實不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM