【问题标题】:Data Tables- Json data could not be parsed in Symfony2数据表-无法在 Symfony2 中解析 Json 数据
【发布时间】: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


【解决方案1】:

不要使用

requirements: { _method: POST }

另外,您确定要使用bServerSide = true吗?

【讨论】:

  • 我不确定bServerSide = true是什么意思,我想从控制器(通过json文件发送)获取要显示在数据表中的数据。谢谢!
  • 这意味着所有处理都在服务器端处理,我认为您不需要。见datatables.net/release-datatables/examples/server_side/…
  • 但是如果我想从“sAjaxSource”中检索数据,我选择指向我的控制器中的一个动作,我是否必须包含 bServerSide=true,或者不?
  • 你看过我刚刚添加的链接了吗?您想从服务器获取数据,但不想在服务器端处理所有内容(分页、排序等)
  • 你检查过你的树枝模板中的输出了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多