[英]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.