[英]DataTable - Invalid JSON response when retrieved from PHP
我知道这是一个常见问题,但我有另一个问题。
我的数据表具有以下jquery配置:
$( document ).ready(function() {
$('#example').dataTable({
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
},
"bProcessing": true,
"sAjaxSource": "response.php",
"aoColumns": [
{ mData: 'id' } ,
{ mData: 'name' },
{ mData: 'description' }
//{ mData: 'img', render: getImg },
]
});
});
从php生成的json(如果直接从文件中加载,则可以使用):
{
"sEcho": 1,
"iTotalRecords": 10,
"iTotalDisplayRecords": 10,
"aaData": [{
"id": "1",
"name": "Salsa estilo Casino",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "2",
"name": "Salsa estilo Son",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "3",
"name": "Salsa LA",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "4",
"name": "Salsa NY",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "5",
"name": "Bachata",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "6",
"name": "Reggaeton",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "7",
"name": "Chachacha",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "8",
"name": "Rumba",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "9",
"name": "Pachanga",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "10",
"name": "Ritmos tradicionais cubanos",
"description": "Descri\u00e7\u00e3o ..."
}]
}
我的PHP response.php
文件:
<?php
// my database classe with CRUDed POJOs.
include_once '../admin/db.php';
// That was from a sample code that worked fine.
$data = array(
array('Name'=>'Descrição ...', 'Empid'=>11, 'Salary'=>101, 'img' => '../img/lais.jpg'),
array('Name'=>'alam', 'Empid'=>1, 'Salary'=>102, 'img' => '../img/lais.jpg'),
array('Name'=>'phpflow', 'Empid'=>21, 'Salary'=>103, 'img' => '../img/lais.jpg')
);
/* Query the database and retrive in $data2[0] the total number of rows
and $data2[1] an array of arrays with the following format (as described above):
array(
array('id' => '1', 'name' => 'name', 'description' => 'Desc ...'),
...
)
*/
$data2 = Turma::fetchAllAssoc();
$results = array(
"sEcho" => 1,
"iTotalRecords" => 10,
"iTotalDisplayRecords" => 10,
"aaData"=>$data2[1]);
header('Content-Type: application/json');
echo json_encode($results);
?>
我究竟做错了什么? 这似乎是我的错误。
解决了我的问题。
在PHP中, response.php
仅返回浏览器中显示的json内容。
错误是:有一些html注释的内容似乎隐藏在`include_once'../admin/db.php';中,甚至包括注释的html标签。
当我添加行header('Content-Type: application/json');
似乎丢失的所有内容都显示在浏览器中。
擦除所有内容,甚至注释掉html标记以仅输出(回显) json_encode($results);
。 然后,一切工作顺利。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.