PHP-AAJAX:如何通过PHP/json数组从查询中填充jquery数据表


PHP-AJAX: How to populate jquery datatables from a query through php / json array

我刚刚开始研究DatatablesjQuery插件,我很难让它与我当前的工作一起工作。

我通常使用AJAX回调来填充表,方法是从数组中获取我想要的值,并通过PHP脚本查询数据库。就我在数据表网站上所读到的内容而言,类似的事情是可能的,但我总是会出错,所以我只会发布我迄今为止所做的事情,希望有人能帮助我。

这就是我用一些ajax参数调用数据库的方式。

<script>
$(document).ready( function () {
    $('#test_table').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "test.php",
            "type": "POST"
        },
        "columns": [
            { "data": "id" },
            { "data": "name" },
            { "data": "email" }
        ]
    });
} );
</script>

这就是php端的样子。

$sql = "SELECT * FROM test_table";
$res = mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));
$columns = array(
            array('db' => $row['id'], 'dt' => 'id'),
            array('db' => $row['name'], 'dt' => 'name'),
            array('db' => $row['email'], 'dt' => 'email'),
    );
echo json_encode($columns);

然而,我收到一个错误,说"数据没有定义"。(注意。我阅读了数据表网站上的文档,但我并没有一步一步地遵循它。我把它作为我试图完成的任务的参考。数据表服务器端POST

我可能完全错了,但我不想对代码做太多更改,所以我尝试了一种我认为可行的方法。如果有人能告诉我如何通过php>json数组调用查询数据库来填充数据表,我将不胜感激。

提前感谢,

感谢大家的投入。我想了个办法让它发挥作用。

我希望能够在jquery回调中将数据发送到数据表,因为这将允许我在数据表之外创建自己的搜索。我的方法是运行一个ajax调用,该调用对数据库执行查询,然后将查询结果传递给数据表,但问题是如何以数据表可以接受的方式格式化数据,以及如何让它读取数据以显示在表上。

简单的ajax调用和填充数据表

这个代码可以进一步修改(在我的情况下我会这样做(,但它应该让你知道如何完成我一直想做的事情。

<script>
$('document').ready(function()
{
    $.ajax({
    type : 'POST',
    url  : 'test.php',
    dataType: 'json',
    cache: false,
    success :  function(result)
        {
            //pass data to datatable
            console.log(result); // just to see I'm getting the correct data.
            $('#test_table').DataTable({
                "searching": false, //this is disabled because I have a custom search.
                "aaData": [result], //here we get the array data from the ajax call.
                "aoColumns": [
                  { "sTitle": "ID" },
                  { "sTitle": "Name" },
                  { "sTitle": "Email" }
                ] //this isn't necessary unless you want modify the header
                  //names without changing it in your html code. 
                  //I find it useful tho' to setup the headers this way.
            });
        }
    });
});
</script>

test.php

这是我用来测试的简单版本。我的实际代码要大得多,因为它有几个部分用于查询和搜索。

<?php
$columns = array( 
// datatable column index  => database column name
    0 => 'id',
    1 => 'name',
    2 => 'email',
);
$sql = "SELECT * FROM test_table";
$res = mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));
$dataArray = array();
while( $row = mysqli_fetch_array($res) ) {

    $dataArray[] = $row["id"];
    $dataArray[] = $row["name"];
    $dataArray[] = $row["email"];
}
echo json_encode($dataArray);
?>

这简化了很多事情,至少对我来说是这样。我不想包含额外的库"ssp.class.php"。我也不想进入PDO。因此,这使它变得更加灵活,我希望它能帮助其他试图完成类似任务的人。

经过24小时的试用&错误,这个代码对我有效。

$(document).ready(function () {
    $('#example').DataTable({
        processing: true,
        serverSide: false, // if true, causes Showing **0 to 0 of 0 entries (filtered from NaN total entries)** error in datatable
        ajax: {
            url: 'fetchCustomers.php',
            type: 'POST',
            dataSrc: ''
        },
        columns: [
            { data: 'Name' },
            { data: 'Position' },
            { data: 'Office' },
            { data: 'Age' },
            { data: 'Start_Date' },
            { data: 'Salary' }
        ],
    });
}); // end of $(document).ready(function (){);

以下是PHP文件的代码:

<?php
$host = "localhost";
$user = "root";
$password = "********";
$dbname = "data_table";
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {  die("Connection failed: " . mysqli_connect_error()); }
$return_array = array();
$query = "SELECT * FROM customer";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
    $Name = $row['Name'];
    $Position = $row['Position'];
    $Office = $row['Office'];
    $Age = $row['Age'];
    $Start_Date = $row['Start_Date'];
    $Salary = $row['Salary'];
    $return_array[] = array (
                    "Name" => $Name,
                    "Position" => $Position,
                    "Office" => $Office,
                    "Age" => $Age,
                    "Start_Date" => $Start_Date,
                    "Salary" => $Salary
                );
}
// Encoding array in JSON format
echo json_encode($return_array);
?>
$columns = array(
 'data'=>
   array(
        $row[0]['id'],
        $row[0]['name'],
        $row[0]['email'],
   )
);

格式正确吗

UPDATE:您不循环结果

如果您想使用服务器端处理,您需要包括服务器端助手类ssp.class.php并使用它,如本例所示。

例如:

// DB table to use
$table = 'test_table';
// Table's primary key
$primaryKey = 'id';
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case object
// parameter names
$columns = array(
    array( 'db' => 'id',    'dt' => 'id' ),
    array( 'db' => 'name',  'dt' => 'name' ),
    array( 'db' => 'email', 'dt' => 'email' )
);
// SQL server connection information
$sql_details = array(
    'user' => '',
    'pass' => '',
    'db'   => '',
    'host' => ''
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */
require( 'ssp.class.php' );
echo json_encode(
    SSP::simple( $_POST, $sql_details, $table, $primaryKey, $columns )
);