我的桌子为什么不显示?

时间:2016-11-09 17:17:17

标签: php json datatables

我在我建立的网站上使用了几张表格。我已经开始使用DataTables并尝试转换为使用服务器端处理。我按照示例here进行了修改,以使用我已有的内容。这是完成的文件( ServerSide.php ):

<?php
$Page = '';
if (isset($_GET['PageName']))
{
    //echo "<br>Page = Get<br>";
    $Page = $_GET['PageName'];
}
elseif (isset($_POST['PageName']))
{
    //echo "<br>Page = Post<br>";
    $Page = $_POST['PageName'];
}
//For testing just this page
//if($Page == '')
//{
//  $Page = 'TableHeadings';
//}

include 'DBConn.php';
$headings = array();
$hsql = "select Headings from TableHeadings where TableName = '$Page' order by Id";
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$CountHeadings = count($rHeadings);
$tsqlHeadings = '';
$ColumnHeader = array();
for ($row = 0; $row < $CountHeadings; $row++)
{
    $headings[$row] = $rHeadings[$row]["Headings"];
    $tsqlHeadings = $tsqlHeadings . "[" . $headings[$row] . '],';
}

foreach($headings as $index => $columnName)
{
    $ColumnHeader[] = array('db'=>$columnName,'dt'=>$index);
}

//DB table to use
$table = $Page;

//Table's primary key
$primaryKey = 'id';

//Array of database columns which should be read and sent back to DataTables
$columns = $headings;

//SQL server connection information
$sql_details = array(
    'user'=> 'EngsysWebUser',
    'pass'=> 'Fr0ntier2016',
    'db'=> 'EngSys',
    'host'=> 'MAFINFWWAPV01'
);
$connectionInfo = array( "Database"=>$dbname, "UID"=>$username, "PWD"=>$password);
$conn = sqlsrv_connect( $servername, $connectionInfo );
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
}

// Get data to display 
$Query = "
    SELECT count($primaryKey) over() as Row_Count, ".str_replace(" , ", " ", implode(", ", $columns))."
    FROM   $table";

$rResult = sqlsrv_query( $conn, $Query );
if( $rResult === false) {
    die( print_r( sqlsrv_errors(), true) );
}

// Data set length after filtering
$iFilteredTotal = sqlsrv_num_rows( $rResult );

// Total data set length 
$sQuery = "SELECT COUNT($primaryKey)
    FROM $table";
$rResultTotal = sqlsrv_query( $conn, $sQuery );
$aResultTotal = sqlsrv_fetch_array( $rResultTotal, SQLSRV_FETCH_ASSOC);
$iTotal = $aResultTotal;

// Output
$output = array(
    "iTotalRecords" => $iTotal,
    "iTotalDisplayRecords" => $iFilteredTotal,
    "Data" => array()
);

while ( $aRow = sqlsrv_fetch_array( $rResult,SQLSRV_FETCH_ASSOC ) )
{
    $row = array();
    for ( $i=0 ; $i<count($columns) ; $i++ )
    {
        if ( $columns[$i] == "version" )
        {
            // Special output formatting for 'version' column 
            $row[] = ($aRow[ $columns[$i] ]=="0") ? '-' : $aRow[ $columns[$i] ];
        }
        else if ( $columns[$i] != ' ' )
        {
            // General output 
            $row[] = $aRow[ $columns[$i] ];
        }
    }
    $output['Data'][] = $row;
}

echo json_encode($output);
?>

然后我有我的另一个文件,如果我正确理解它应该调用前一个文件( ServerSide.php )并将格式化为表格的json响应放入tbody我的表( RunningServerSide.php ):

<?php
$Page = '';
if (isset($_GET['PageName']))
{
    $Page = $_GET['PageName'];
}
elseif (isset($_POST['PageName']))
{
    $Page = $_POST['PageName'];
}
include 'DBConn.php';
$headings = array();
$hsql = "select Headings from TableHeadings where TableName = '$Page' order by Id";
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$CountHeadings = count($rHeadings);
$tsqlHeadings = '';
$ColumnHeader = array();
for ($row = 0; $row < $CountHeadings; $row++)
{
    $headings[$row] = $rHeadings[$row]["Headings"];
    $tsqlHeadings = $tsqlHeadings . "[" . $headings[$row] . '],';
}
$Edit = 0;
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <?php require 'StyleLinks.php'; ?>
        <?php include 'DataTableLinks.php'; ?>
    </head>
    <body>
        <table class="NormalTable display nowrap"  style="width: 100%; border: 1px" id="DataTable">
                <thead>
                    <tr><?php echo "\n";
                            if($Edit == 1)
                            {?>
                        <th class="cell">Edit</th><?php echo "\n";                          
                            }
                            foreach($headings as $heading)
                            {?>
                        <th class="cell"><?php echo $heading; ?></th><?php echo "\n";
                            }?>
                    </tr>
                </thead><?php echo "\n";?>
            </table>
    </body>
</html>

然后为了清楚起见,我在第二个文件的head中包含了几个文件,用于样式设置。它们包括我为表创建的CSS以及我从DataTables下载的文件以获取其格式。另外在 DataTableLinks.php 文件中,我有这个来初始化DataTable:

<script>
    $(document).ready(function ()
    {
        $('#DataTable').DataTable(
      {
          "lengthMenu": [[25, 50, 75, 100, 150], [25, 50, 75, 100, 150]],
          "ScrollX": true,
          "dom": '<"top"Biflp<"clear">>rt<"bottom"ip<"clear">>',
          buttons: [{ extend: 'collection', text: 'Selection', buttons: ['selectAll', 'selectNone'] }, { extend: 'collection', text: 'Export', buttons: ['excel', 'csv', 'pdf']}],
          fixedHeader: { header: true, footer: false },
          select: true,
          "processing": true,
          "serverSide": true,
          "ajax": { "url": "ServerSide.php", "dataType": "jsonp", "success": function(data){$('#DataTable').append(data);} }
      });
    });
</script>

我一直致力于纠正我在控制台(F12)中发现的问题,并且不再存在任何问题。但我仍然只得到2个按钮和表头,然后弹出一个说:

  

DataTables警告:table id = DataTable - 无效的JSON响应。有关此错误的详细信息,请参阅http://datatables.net/tn/1

该错误消息中的链接表示要检查开发人员工具的网络部分中的响应。在那里,它看起来很好,但我以前从未使用过DataTables,而且我现在只使用JSON和AJAX大约一周。响应如下:

Respnse

预览标签如下:

enter image description here

1 个答案:

答案 0 :(得分:1)

你ajax应该有一个成功的功能,一旦成功,它应该对收到的响应做些什么。下面我告诉我将响应附加到数据表。只是一个基本想法

$.ajax({

  "url": "ServerSide.php",
  "dataType": "jsonp",
  "success": function(response) {
     $('#DataTable').append(response);
   }
})

编辑:按照会话修改您的文件,如下所示。

RunningServerSide.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>

    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
    <script src="//code.jquery.com/jquery-1.12.3.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <style>
        td {text-align:center;}
    </style>
</head>
<body>
<table class="NormalTable display nowrap"  style="width: 100%; border: 1px" id="DataTable">

    </table>

<script>
    $(document).ready(function ()
    {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            url: 'ServerSide.php',
            success: function(response) {
                $('#DataTable').append(response).DataTable({
                    bSort: false,
                    aoColumns: [ { sWidth: "45%" }, { sWidth: "45%" }, { sWidth: "10%", bSearchable: false, bSortable: false } ],
                    "scrollY":        "200px",
                    "scrollCollapse": true,
                    "info":           true,
                    "paging":         true
                } );

            }
        })

    });
</script>
</body>
</html>

ServerSide.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tester";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM mike";
$result = $conn->query($sql);

echo "<thead>
                <tr>
                    <th>ID</th>
                    <th>TableName</th>
                    <th>Headings</th>
                </tr>
                </thead>
                <tfoot>
                <tr>
                    <th>ID</th>
                    <th>TableName</th>
                    <th>Headings</th>
                </tr>
                </tfoot>
                <tbody>";
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

        echo"<tr><td>" . $row["Id"]. "</td><td>" . $row["TableName"]. "</td><td>" . $row["Headings"]. "</td></tr>";

    }
} else {
    echo "0 results";
}

echo"</tbdoy>";
$conn->close();
?>