2016-11-09 131 views
0

我有幾個表格用於在我建立的網站上進行報告。我已經開始使用DataTable,並試圖轉換爲使用服務器端處理。我遵循示例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文件,我有這樣的初始化數據表:

<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警告:表id = DataTable - 無效的JSON響應。有關此錯誤的更多信息,請參閱http://datatables.net/tn/1

該錯誤消息中的鏈接表示檢查開發人員工具的網絡部分中的響應。在那裏它對我來說看起來很好,但是我從來沒有使用過DataTable,而現在我只使用JSON和AJAX工作了一週。該反應是這樣的:

Respnse

和預覽標籤是這樣的:

enter image description here

+1

[小博](http://bobby-tables.com/)說***腳本有風險SQL注入攻擊。](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***。即使[轉義字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! *** SQL注入!*** *這不僅僅是爲了早餐!* –

+0

你沒有成功的功能ajax –

+0

@JayBlanchard這是一個內部唯一的網站,這樣就會限制威脅。並且沒有用於向我的SQL添加任何內容的開放文本框,只有幾個下拉列表。我計劃將SQL轉換爲使用PDO'prepare'語句,但我希望首先得到這個工作。 – Mike

回答

1

你阿賈克斯應該有一個成功的功能,以什麼應該它一旦接收到響應做是成功的。下面我告訴將響應追加到數據表中。只是一個基本的想法

$.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(); 
?> 
+0

所以這將與'腳本'是初始化DataTable?或者這是一個我需要的獨立腳本? – Mike

+0

用此修改你的腳本。 –

+0

我嘗試在''ajax':'部分內部添加''success':function(data){$('#DataTable')。append(data);}'來初始化DataTable。 。但它似乎沒有做任何事情。我怎麼知道'function(data)'應該被調用。我認爲它會是'data'或'response',但都不會返回任何東西。 – Mike