【发布时间】:2012-10-12 19:07:17
【问题描述】:
我不断收到此错误:
DataTables 警告:无法解析来自服务器的 JSON 数据。这是由 JSON 格式错误引起的。
我不确定是什么问题。是不是路由不正确?我验证了http://jsonlint.com/生成的json文件是有效的。
控制器: 公共函数 indexAction($id) {
return $this-render('CetiucValidateSurveyBundle:Validate:validatespreadsheet.html.twig');
}
包含 javascript 和表格的 twig(view) 文件。
validatespreadsheet.html.twig':
<table id="myDataTable" >
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
</tbody>
用于从控制器检索表数据的 javascript:
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$('#myDataTable').dataTable(
{
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "{{ path('CetiucValidateSurveyBundle_renderJson')}}"
}
);
});
控制器中将数据返回给视图的方法
public function renderJsonAction(Request $request)
{
$arr = array ('aaData' => array(
array('3','35','4', '$14,500', '$15,200','$16,900','5','1'),
array('1','16','4', '$14,200', '$15,100','$14,900','Running','1'),
array('5','25','4', '$14,500', '$15,600','$16,900','Not Running','1')
)
);
$post_data = json_encode($arr);
return new Response( $post_data,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
}
这是返回 json 的操作的路由条目
CetiucValidateSurveyBundle_renderJson:
defaults: { _controller: "CetiucValidateSurveyBundle:Validate:renderJson" }
pattern: /json
requirements: { _method: POST }
【问题讨论】:
-
如果转到 app_dev.php/validator/json 我得到正确的 Json {"aaData":[["3","35","4","$14,500","$15,200", "$16,900","5","1"],["1","16","4","$14,200","$15,100","$14,900","跑步","1"], ["5","25","4","$14,500","$15,600","$16,900","Not Running","1"]]} 但是当我尝试时仍然遇到同样的错误在视图中使用 Ajax 获取此 Json
标签: jquery jquery-plugins symfony datatables