数据表:未捕获的TypeError:无法读取未定义的属性'length' [英] Datatables: Uncaught TypeError: Cannot read property 'length' of undefined

查看:310
本文介绍了数据表:未捕获的TypeError:无法读取未定义的属性'length'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将ajax源与Datatables一起使用,并且在执行过程中遇到了一些错误.以前Ajax并未与Datatables一起使用,并且它们工作正常,但是在尝试使用Ajax和JSON时出现了一些错误.

我收到的错误如下:

未捕获的TypeError:无法读取未定义的属性'length'

在此文本正下方使用修改后的代码时,不再存在此错误,但DataTables仍然损坏(不进行搜索,分页,排序等).可能有一个生动的示例,所以请尝试以下站点: fogest.com/test

要在页面加载时创建表,请输入以下代码:

$(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"
    } );
} );

并且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 );    

?>

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"}]

该表已正确生成,但由于此错误,在表上方有文字正在处理,并且您无法使用数据表的任何功能,例如搜索."

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

我假设错误出在我的JSON输出中,但是我不完全知道它出了什么问题,也不知道该如何解决.我对Web开发还很陌生,因此实现Datatables确实是一个学习过程!

解决方案

您的JSON输出错误是由于以下原因:

  1. iTotalRecordsiTotalDisplayRecords字段丢失.这就是为什么分页(以及所有其他功能)被破坏的原因(请注意,消息显示1到 NaN 项的 NaN "(从 NaN 总条目)".有关服务器端处理的更多详细信息,请参见此页面.
  2. JSON响应后有一些HTML代码.

这是多余的HTML代码(摘自 test.php ):

<!-- Hosting24 Analytics Code -->
<script src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->

我认为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);

?>

请注意,不建议使用mysql_*函数,因此您应该使用 PDO MySQLi 代替;请查看此答案以了解更多详细信息. >

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.

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

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:

<?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:

[{"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:

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!

解决方案

Your JSON output is wrong for the following reasons:

  1. The iTotalRecords and iTotalDisplayRecords fields are missing. This is why the pagination (and all the other functionalities) are broken (notice the message "Showing 1 to NaN of NaN entries (filtered from NaN total entries)" in the footer section). See this page for further details on server-side processing.
  2. There is some HTML code after the JSON response.

Here is the extra HTML code (taken from test.php):

<!-- Hosting24 Analytics Code -->
<script src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->

In my opinion, the test.php script should be like the following:

<?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 PDO or MySQLi instead; have a look at this answer for further details.

这篇关于数据表:未捕获的TypeError:无法读取未定义的属性'length'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆