我有一个简单的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数据表中,我有:
<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。
如果您有数千条以上的记录,那么使用服务器端处理模式将获得更高的性能。但在这种情况下,我建议使用jQueryDataTables分发版中的ssp.class.php帮助程序库(请参阅examples/server_side/scripts
文件夹)。
发现了问题,这对我来说很愚蠢!在OS X El Capitan(10.11.2)上,php文件没有被Safari或任何其他浏览器识别,因为它们在我的主目录中,而不是在apache的/Library/WebServer/Documents根目录中!
我把我的项目移到了那个目录中,因为我无法像El Capitan之前那样设置使用我的用户目录~/Sites(将来还会做更多的工作)。
有了这一更改,php文档将在ajax参数中包含时执行,并且一切正常!
感谢大家的帮助。很抱歉浪费了时间,但我的test.php工作正常,但我没有注意到它在web服务器根目录中!