[英]json returned from php cannot be parsed for jQuery dataTables
我有一個帶庫書籍的簡單mysql數據庫表。 我正在使用php頁面來檢索書籍列表。 這是返回的內容:
php get_books.php
{"iTotalRecords":"1","aaData":[{"author":"Tim Powers","title":"The Anubis Gates","genre":"Fiction","publisher":null,"year":null,"location":"Bookshelf","notes":null}]}
在jQuery dataTables中,我有:
<script >
$(document).ready(function() {
$('#books').DataTable({
"bServerSide": true,
"sAjaxSource": "./get_books.php"
});
});
</script>
當我使用該腳本運行網頁時,會收到警報:
DataTables警告(表ID ='books'):DataTables警告:無法解析來自服務器的JSON數據。 這是由JSON格式錯誤引起的。
我找不到格式錯誤。 數據應如何格式化。
這是返回JSON數據的php頁面:
<?php
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$offset = ($page-1)*$rows;
$result = array();
include 'conn.php';
$rs = mysql_query("select count(*) from books");
$row = mysql_fetch_row($rs);
$result["iTotalRecords"] = $row[0];
$rs = mysql_query("select * from books limit $offset,$rows");
$items = array();
while($row = mysql_fetch_object($rs)){
array_push($items, $row);
}
$result["aaData"] = $items;
echo json_encode($result);
?>
退貨應該是什么樣子,我該如何生產?
JS和PHP代碼都有很多問題。
如果books
表中的記錄少於幾千條,我建議通過刪除"bServerSide": true
來禁用服務器端處理模式,以啟用客戶端處理模式。
JavaScript :
$(document).ready(function() {
$('#books').DataTable({
"ajax": "get_books.php",
"columns": [
{ "data": "author" },
{ "data": "title" },
{ "data": "genre" },
{ "data": "location" }
]
});
});
PHP:
<?php
include 'conn.php';
$rs = mysql_query("select author, title, genre, location from books");
$result = array();
$items = array();
while($row = mysql_fetch_object($rs)){
array_push($items, $row);
}
$result["data"] = $items;
header("Content-type: application/json");
header("Cache-Control: no-cache, must-revalidate");
echo json_encode($result);
?>
的HTML
<table id="books" class="display tablesorter">
<thead>
<tr>
<th>Author</th>
<th>Title</th>
<th>Genre</th>
<th>Location</th>
</tr>
</thead>
</table>
有關代碼和演示,請參見此jsFiddle 。
如果您有數千條記錄,那么使用服務器端處理模式將獲得更高的性能。 但是在這種情況下,我建議使用jQuery DataTables發行版中隨附的ssp.class.php幫助程序庫(請參見examples/server_side/scripts
文件夾)。
發現了問題,這對我來說很愚蠢! 在OS X El Capitan(10.11.2)上,Safari或任何其他瀏覽器均未識別php文件,因為它們位於我的主目錄中,而不位於apache的/ Library / WebServer / Documents根目錄中!
我將項目移到該目錄中,因為在El Capitan之前,您無法像使用您的用戶目錄〜/ Sites那樣進行任何設置(以后將繼續使用該目錄)。
進行此更改后,php文檔將被執行,因為它們包含在ajax參數中,並且一切正常!
謝謝大家的幫助。 抱歉浪費時間,但是我的test.php可以工作,但是我沒有注意到它在Web服務器的根目錄中!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.