JQuery数据表错误“无法读取未定义的属性'长度'

时间:2015-06-08 00:05:03

标签: php jquery ajax datatable

我从我网站上名为 request.php 的其他网址获取DataTable的数据。

request.php:

$con = mysql_connect("xxxx", "xxxx", "xxxx");
$con or die(mysql_error());
mysql_select_db("xxxx") or die(mysql_error());

$result = mysql_query("SELECT * FROM users_logins") 
or die(mysql_error()); 

$resultArray = array();
$tempArray = array();

while($row = mysql_fetch_assoc($result))
{
    // Add each row into our results array
    $tempArray = $row;
    array_push($resultArray, $tempArray);
}

echo json_encode($resultArray);

mysql_close($con);

这是我的HTML&用于DataTable的JQuery。

table.html:

<head>
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
</head>
<body>
 <table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>uEmail</th>
                <th>Time</th>
                <th>Location</th>
            </tr>
        </thead>


    </table>
  <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
  <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
  <script>


    $(document).ready(function() {
        $('#example').dataTable( {
                "sAjaxSource": "http://xxxx.net/request",
                "sAjaxDataProp": "data"
        } );
    } );
  </script>
</body>

当手动访问 request.php 时,显示的内容如下: [{"uEmail":"xxxx@gmail.com","time":"06-07-2015 7:55 pm","location":"xx.xx.xx.xxx"},{"uEmail":"xxxx@gmail.com","time":"06-07-2015 5:45 pm","location":"xx.xx.xx.xxx"}]

在控制台中,我收到此错误:Uncaught TypeError: Cannot read property 'length' of undefined

以下是DataTable和控制台的屏幕截图。 Screenshot of DataTable and console error

1 个答案:

答案 0 :(得分:3)

根据DataTables 1.9文档,sAjaxDataProp指定包含条目的返回JSON对象内的数组名称。 同时,DataTables似乎接受条目作为数组,而不是对象。

您的退货格式应为:

{"data": [["xxxx@gmail.com","06-07-2015 7:55 pm","xx.xx.xx.xxx"],["xxxx@gmail.com","06-07-2015 5:45 pm","xx.xx.xx.xxx"]]}