我正试图用DataTablejquery插件填充这个HTML表,使用AJAX调用从php脚本接收这个JSON
服务器响应:
{
"newsletters": [{
"anio": "2016",
"mes": "1",
"quincena": "1"
}, {
"anio": "2016",
"mes": "1",
"quincena": "2"
}]
}
HTML文件:
<div id="tabla_newsletters" >
<table id="newsletter_datatable">
<thead>
<tr>
<th>anio</th>
<th>mes</th>
<th>quincena</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script>
$(document).ready(function(){
var table = $('#newsletter_datatable').DataTable( {
ajax: {
url: '/newsletter/getNewsletters',
dataSrc: 'newsletters'
},
columns:[
{ 'newsletters': 'anio' },
{ 'newsletters': 'mes' },
{ 'newsletters': 'quincena' }
],
} );
});
</script>
然后是我的php服务(在symfony 1.4中制作),正如我之前所说的,这是根据JSON在线验证器返回正确的JSON:
public function executeGetNewsletters(sfWebRequest $request){
$conn = Doctrine_Manager::getInstance()->getCurrentConnection();
$qry=$conn->execute("Select anio,mes,quincena from newsletters");
$newsletters = $qry;
$dataNews = array();
$i=0;
foreach ($newsletters as $news)
{
$dataNews[$i] = array(
"anio" => $news['anio'],
"mes" => $news['mes'],
"quincena" => $news['quincena'],
);
++$i;
}
$output = array(
"newsletters" => $dataNews,
);
$json=$this->renderText(json_encode($output));
return $json;
}
Datatable抛出以下错误:
"DataTables警告:table id=newsletter_datable-为行0请求了未知参数"0"。有关此错误的详细信息,请参阅http://datatables.net/tn/4"
我看了其他案例,但乍一看是不同的案例。。。。。
编辑:我已经解决了……问题出在服务器上的脚本上,索引需要是数字。。。。现在它正在正确地填充表格
最终代码:
-服务器现在的响应是(显然插件只接受我在其他人的bug中看到的这种格式):
{"newsletters":[["2016","1","1"],["2016","1","2"]]}
-HTML文件代码为:
<div id="tabla_newsletters" >
<table id="newsletter_datatable">
<thead>
<tr>
<th>anio</th>
<th>mes</th>
<th>quincena</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script>
$(document).ready(function(){
var table = $('#newsletter_datatable').DataTable( {
ajax: {
url: '/newsletter/getNewsletters',
dataSrc: 'newsletters'
}
} );
});
</script>
php服务代码是(我只将关联数组的索引从字段名更改为数字):
public function executeGetNewsletters(sfWebRequest $request){
$conn = Doctrine_Manager::getInstance()->getCurrentConnection();
$qry=$conn->execute("Select anio,mes,quincena from newsletters");
$newsletters = $qry;
$dataNews = array();
$i=0;
foreach ($newsletters as $news)
{
$dataNews[$i] = array(
"0" => $news['anio'],
"1" => $news['mes'],
"2" => $news['quincena'],
);
++$i;
}
$output = array(
"newsletters" => $dataNews,
);
$json=$this->renderText(json_encode($output));
return $json;
}
仅供参考:只要做对了,你就可以解决原来的问题:
columns:[
{ data: 'anio' }, //NOT { 'newsletters': 'anio' }
{ data: 'mes' },
{ data: 'quincena' }
],
使用data
可以定义每个时事通讯项目中应进入该列的属性。