json 数据表:未捕获的类型错误:无法读取未定义的属性“长度”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14057459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Datatables: Uncaught TypeError: Cannot read property 'length' of undefined
提问by ComputerLocus
I'm attempting to use an ajax source with Datatables, and I've run into some errors in doing. Previously Ajax was not being used with Datatables, and they were working fine, but upon trying to use Ajax and JSON I have some errors.
我正在尝试将 ajax 源与数据表一起使用,但在执行过程中遇到了一些错误。以前 Ajax 没有与 Datatables 一起使用,并且它们工作正常,但是在尝试使用 Ajax 和 JSON 时我遇到了一些错误。
The error I am recieving is the following:
我收到的错误如下:
Uncaught TypeError: Cannot read property 'length' of undefined
未捕获的类型错误:无法读取未定义的属性“长度”
Edit: Upon using the revised code directly below this text, this error is no longer present but DataTables are still broken (no searching, pagination, sorting, etc...). It may help to have a live example, so try this site: fogest.com/test
编辑:在此文本正下方使用修改后的代码后,此错误不再存在,但数据表仍然损坏(没有搜索、分页、排序等)。有一个活生生的例子可能会有所帮助,所以试试这个网站:fogest.com/test
To create the tables when the page loads here is the code:
在页面加载时创建表格是代码:
$(document).ready(function() {
$('#trades').dataTable( {
"sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"bProcessing": true,
"bServerSide": true,
"aoColumns": [
{ "mData": "id" },
{ "mData": "Minecraft_Username" },
{ "mData": "Block_Name" },
{ "mData": "Quantity" },
{ "mData": "Cost" },
{ "mData": "Trade_Status" },
],
"sAjaxSource": "test.php"
} );
} );
And sAjaxSource test.php contains the following:
sAjaxSource test.php 包含以下内容:
<?php
$tableName = "mctrade_trades";
$result = mysql_query("SELECT `id`, `Minecraft_Username`, `Block_Name`, `Quantity`, `Cost`, `Trade_Status` FROM $tableName");
$data = array();
while ( $row = mysql_fetch_assoc($result) )
{
$data[] = $row;
}
header("Content-type: application/json");
echo json_encode( $data );
?>
The output of test.php:
test.php 的输出:
[{"id":"1","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"100","Trade_Status":"1"},{"id":"2","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"1002","Trade_Status":"1"},{"id":"3","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"1035","Trade_Status":"1"},{"id":"4","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"1035","Trade_Status":"1"},{"id":"5","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"100","Trade_Status":"2"},{"id":"6","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"100","Trade_Status":"2"},{"id":"7","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"10000","Trade_Status":"2"}]
The table is generated correctly but due to this error, there is text saying "Processing right above the table, and you cannot use any of the functions of the datatable, such as searching.
表格生成正确,但由于这个错误,有文字说“在表格正上方处理,您不能使用数据表的任何功能,例如搜索。
Here is an image of what the table looks like using the above JSON:

这是使用上述 JSON 的表格外观的图像:

I'm assuming the error is in my JSON output, but I do not exactly know what is wrong with it, nor what I should do to fix it. I'm pretty new to Web Development and implementing Datatables has been quite the learning curve!
我假设错误出在我的 JSON 输出中,但我不完全知道它有什么问题,也不知道我应该怎么做来修复它。我是 Web 开发的新手,实现 Datatables 的学习曲线相当不错!
回答by
Your JSON output is wrong for the following reasons:
您的 JSON 输出错误,原因如下:
- The
iTotalRecordsandiTotalDisplayRecordsfields are missing. This is why the pagination (and all the other functionalities) are broken (notice the message "Showing 1 to NaNof NaNentries (filtered from NaNtotal entries)" in the footer section). See this pagefor further details on server-side processing. - There is some HTML code after the JSON response.
- 该
iTotalRecords和iTotalDisplayRecords字段缺失。这就是分页(和所有其他功能)被破坏的原因(注意页脚部分中的消息“显示 1 到NaNof NaN条目(从NaN总条目中过滤)”)。有关服务器端处理的更多详细信息,请参阅此页面。 - JSON 响应后有一些 HTML 代码。
Here is the extra HTML code (taken from test.php):
这是额外的 HTML 代码(取自test.php):
<!-- Hosting24 Analytics Code -->
<script src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
In my opinion, the test.phpscript should be like the following:
在我看来,test.php脚本应该如下所示:
<?php
$link = mysqli_init();
// Adjust hostname, username, password and database name before use!
$db = mysqli_real_connect($link, "hostname", "username", "password", "database") or die(mysqli_connect_error());
$SQL = 'SELECT `id`,`Minecraft_Username`,`Block_Name`,`Quantity`,`Cost`,`Trade_Status` FROM mctrade_trades';
$result = mysqli_query($link, $SQL) or die(mysqli_error($link));
$aaData = array();
while ($row = mysqli_fetch_assoc($result)) {
$aaData[] = $row;
}
$response = array(
'aaData' => $aaData,
'iTotalRecords' => count($aaData),
'iTotalDisplayRecords' => count($aaData)
);
if (isset($_REQUEST['sEcho'])) {
$response['sEcho'] = $_REQUEST['sEcho'];
}
header('Content-type: application/json');
echo json_encode($response);
?>
Be also aware that the mysql_*functions are deprecated, so you should use PDOor MySQLiinstead; have a look at this answerfor further details.

