【问题标题】:Send POST parameters to PHP in ajax call of jQuery datatable在 jQuery 数据表的 ajax 调用中向 PHP 发送 POST 参数
【发布时间】:2019-07-04 16:23:47
【问题描述】:

我想在其中创建一个 jQuery 函数,获取输入值,将其发送到 PHP 文件以在 mysql 中进行查询并使用接收到的信息填充数据表。

我遇到的另一个问题是表在用户登录时被初始化,我不知道这是否会妨碍我想做的功能。

这张桌子:

Table and button

这是我初始化它的地方:


    $.fn.dataTable.ext.errMode = 'none';
    var table = $('#m3_sem').DataTable( {

        "ajax": "dist/ajax/prueba_m3_sem.php",
        "paging":   false,
        "ordering": false,
        "info":     false,
        "searching": false,
        "columns": [
            { "data": "resistencia" },
            { "data": "res1" },
            { "data": "res2" },
            { "data": "res3" },
            { "data": "res4" },
            { "data": "res5" },
            { "data": "res6" },
            { "data": "total" }
        ],
        "order": [[0, 'asc']],
        "pagingType": "full_numbers",
        "language": {
            "sSearch" : "Buscar:",
            "lengthMenu": "Mostrando _MENU_ registros por pagina",
            "zeroRecords": "No hay pedidos pendientes",
            "info": "Mostrando pagina _PAGE_ de _PAGES_",
            "infoEmpty": "Sin registros",
            "infoFiltered": "(Filtrados de _MAX_ registros totales)",               
            "paginate" : {
                "first" : "Primera pagina",
                "previous" : "Anterior",
                "next" : "Siguiente",
                "last" : "Ultima pagina"
            }
        }
    });

} );

这是 PHP 文件“prueba_m3_sem.php”,它生成我用来填充表格的 JSON:

$sql = "SELECT DISTINCT resistencia ";
$sql.= "FROM registros ORDER BY resistencia";

$query=mysqli_query($conexion, $sql) or die("ajax-grid-data.php: get PO");

$data = array();
while( $row=mysqli_fetch_array($query) ) {

    $sumtot = 0;
    $nestedData=array();
    $nestedData["resistencia"] = $row["resistencia"];
    $sqld = "SELECT DISTINCT(fecha_entrega) FROM registros where sem_entrega = ".date("W")." and YEAR(fecha_entrega) = ".date("Y")." ORDER BY fecha_entrega";
    $queryd=mysqli_query($conexion, $sqld) or die("ajax-grid-data.php: get PO");
    $count = 0;
    $tot = 0;
    while( $rowd=mysqli_fetch_array($queryd) ) {

        $count++;
        $m3tot = 0;
        $sqlm = "SELECT m3 FROM registros WHERE fecha_entrega = '".$rowd["fecha_entrega"]."' AND resistencia =".$row["resistencia"]."";
        $querym=mysqli_query($conexion, $sqlm) or die("ajax-grid-data.php: get PO");
        while( $rowm=mysqli_fetch_array($querym) ) {

            if (empty($rowm['m3'])){

                $m3 = 0;

            }else{

                $m3 = $rowm["m3"];

            }

            $m3tot = $m3tot + $m3;

        }

        $tot = $tot + $m3tot;
        $nestedData["res".$count] = $m3tot;
        $sumtot = $sumtot + $m3tot;
    }


    $nestedData["total"] = "<b>".$sumtot."</b>";
    $data[] = $nestedData;

}

$sqld2 = "SELECT DISTINCT(fecha_entrega) as fecha FROM registros where sem_entrega = ".date("W")." and YEAR(fecha_entrega) = ".date("Y")." ORDER BY fecha_entrega";
//echo $sqld;
$queryd2=mysqli_query($conexion, $sqld2) or die("ajax-grid-data.php: get PO");
$totm3 = 0;
$nestedData["resistencia"] = "<b>Total</b>";
$count = 0;
while( $rowd2=mysqli_fetch_array($queryd2) ) {

    //echo $rowd["fecha"]."</br>";
    $sqltot = "SELECT SUM(m3) AS m3 from registros WHERE fecha_entrega ='".$rowd2["fecha"]."'";
    $querytot=mysqli_query($conexion, $sqltot) or die("ajax-grid-data.php: get PO");
    while( $rowtot=mysqli_fetch_array($querytot) ){

        $count ++;
        //echo $rowtot["m3"]."</br>"
        $nestedData["res".$count] = "<b>".$rowtot["m3"]."</b>";
        $totm3 = $totm3 + $rowtot["m3"];

    }

}

$nestedData["total"] = "<b>".$totm3."</b>";
$data[] = $nestedData;

$json_data = array("data" => $data);
echo json_encode($json_data);

我已经看过一些代码示例和数据表文档,但我就是找不到适合我需要的函数的东西,或者我只是不太了解它。

另外,如您所见,英语不是我的母语。我希望你能原谅我的拼写错误。

非常感谢您的回复。

【问题讨论】:

    标签: php jquery html ajax datatables


    【解决方案1】:

    据我了解,您想在提交一些搜索值后在表格中显示一些结果?如果是这样的话,这里是我使用员工样本数据库和 mysql 做的一个小例子:

    html:

    <div class="container">
            <input type="text" name="txtName" id="txtName" value="">
            <button type="btn btn-default" name="button" id="btnSearch">Search</button>
        </div>
        <div class="container" id="tblResult" style="display:none;">
            <div class="row">
                <div class="col-sm-6">
                    <table id="example" class="table table-responsive" style="width:100%">
                        <thead>
                            <tr>
                                <th>Cliente</th>
                                <th>Nombre</th>
                                <th>Apellido</th>
                                <th>Device Id.</th>
                                <th>Client id</th>
                                <th>Accion</th>
                            </tr>
                        </thead>
                        <tfoot>
                            <tr>
                                <th>Cliente</th>
                                <th>Nombre</th>
                                <th>Apellido</th>
                                <th>Device Id.</th>
                                <th>Client id</th>
                                <th>Accion</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    

    在此示例中,我使用输入通过名称参数搜索员工,因此如果您想按日期过滤,它不会有那么不同。

    javascript:

    $(document).ready(function(){
    // click event to call the datatable request
    $('#btnSearch').on('click', (event) => {
        let search = $('#txtName').val();// get the input value
        if (search != "") {// validate that the value is  not empty
        //assing the datatable call to a variable
        let example = $('#example').DataTable({
            "destroy": true,
            "responsive":{//this is usefull if you want to use a full responsive datatable just add the responsive css from dataTables.net
                "details": {
                    renderer: function ( api, rowIdx, columns ) {
                        var data = $.map( columns, function ( col, i ) {
                            return col.hidden ?
                            '<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
                            '<td>'+col.title+':'+'</td> '+
                            '<td>'+col.data+'</td>'+
                            '</tr>' :
                            '';
                        } ).join('');
    
                        return data ?$('<table/>').append( data ) :false;
                    }
                }
            },
            "autoWidth": false,//
            "ajax": {
                "url": 'request.php',
                "method": 'POST',
                data:{action:"SLC",name:search}//parameter to search and the action to perform
            },
            "columns": [
                {"data": "emp_no"},
                {"data": "first_name"},
                {"data": "last_name"},
                {"data": "gender"},
                {"data": "salary"},
                {"data": "title"}
            ],
            "language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},//load all dataTables default values in spanish
            "columnDefs": [
                {
                    "className": "dt-center", "targets": "_all"
                }
            ]
        });//fin obtener tabla
        example.on( 'xhr', function ( e, settings, json ) {// check is the response is not null and show the table
            if (json != null) {
                $('#tblResult').css("display","");
            }
        } );
    }
    });
    }); //end ready
    

    如您所见,我调用 dataTable 方法直到执行搜索,如果响应不为空,我也会显示表。

    php:

    <?php
     $host = '127.0.0.1';
     $db   = 'employees';
     $user = 'root';
     $pass = '';
     $charset = 'utf8mb4';
     $pdo = "";
     $options = [
         \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
         \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
         \PDO::ATTR_EMULATE_PREPARES   => false,
     ];
     $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
     try {
         $pdo = new PDO($dsn, $user, $pass, $options);
     } catch (\PDOException $e) {
         throw new \PDOException($e->getMessage(), (int)$e->getCode());
     }
    // a fucntion that display the employees by our search value
     function getEmployeesBySearch($conn,$order,$name) {
    
         $sql = "SELECT e.emp_no,e.first_name,e.last_name,e.gender, gs.salary, gt.title
         FROM employees e
         inner join (
             SELECT  s.emp_no,MAX(s.salary) AS salary
             FROM salaries s
             GROUP by s.emp_no
         ) as gs on e.emp_no = gs.emp_no
         inner join (
             SELECT t.emp_no ,t.title ,MAX(t.from_date) as from_date
             FROM titles t
             WHERE t.to_date = '9999-01-01'
             GROUP BY t.emp_no,t.title
         ) gt on e.emp_no = gt.emp_no
         WHERE gt.title = 'Senior Engineer'
         AND e.emp_no BETWEEN 10001 and 11819";
         //use  bind parameters and prepared statement to do the search and prevent sql injection
         if ($name != "") {
             $sql .= " AND e.first_name like CONCAT( '%', :name, '%')";
         }
    
         if ($order == "DESC") {
             $sql .= " ORDER BY gs.salary DESC";
         }else {
             $sql .= " ORDER BY gs.salary ASC";
         }
         $json= array();
    
         $stmt = $conn->prepare($sql);
         if ($name != "") {
             $stmt->bindParam(':name', $name, PDO::PARAM_STR, 100);
         }
         $stmt->setFetchMode(PDO::FETCH_ASSOC);
         $stmt->execute();
         $rows = $stmt->fetchAll();
         //store the data inside an array
         foreach ($rows as $row) {
             $tempArray = array(
                 'emp_no'=>$row["emp_no"],
                 'first_name'=>$row['first_name'] ,
                 'last_name'=>$row['last_name'],
                 'gender'=>$row['gender'],
                 'salary'=>$row['salary'],
                 'title'=>$row['title']
             );
             //json encode the array and send the response back
             $json["data"][] = $tempArray;
         }
         echo json_encode($json);
     }
    
     if (isset($_POST["action"])) {
         // we set the variables here, since you will add another stuff later I decided a switch to run a specific case with the action the user send
         $action = $_POST["action"];
         $order = (isset($_POST["order"]) ? $_POST["order"] : "");
         $name = (isset($_POST["name"]) ? $_POST["name"] : "");
         switch ($action) {
             case 'SLC':
             getEmployeesBySearch($pdo,$order,$name);
            break;
         }
     }
     ?>
    

    我在这里使用一个简单的连接和一个从我的数据库加载结果以将它们作为 json 响应发送回的函数,还尝试在您的查询中使用准备好的语句并像示例一样绑定参数

    希望对你有帮助 =)

    【讨论】:

    • 你的例子很容易理解,但现在我有一个问题。看起来当我单击按钮时发送了请求,但随后它卡在“加载”中。这是我制作的结果代码:jsfiddle.net/c62ojpta
    • 您可以在开发控制台中看到您的请求是否得到任何答复?您还从 datatable 收到任何警报吗?如果您没有收到任何警报或答案,那么问题出在您的 php 代码中
    • 我只有 1 个错误,但它与数据表或请求无关。这也是我的 PHP 代码:phpfiddle.org/main/code/7pze-k0nw
    • 我的理解是,您正在每个电阻器中寻找 m3 并创建某种数组来返回?您是否调试您的 php 代码以查看它是否在特定请求中返回预期的答案?
    • 是的,我调试了它,但它没有显示错误。即使您使用不存在的一周数,php 也会在每个电阻(电阻)中为您抛出零
    猜你喜欢
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多