cakephp 3.x和datatable示例

时间:2017-06-18 15:00:22

标签: ajax cakephp datatable cakephp-3.4

我是新蛋糕php 3.4,我正在尝试用ajax请求和数据表构建一个示例 这是我的控制器:

 public function getdata(){

if ($this->request->is('ajax')) {
    $cc = array(
            array('nome'=>'parvez', 'cognome'=>'AA', 'email'=>'101'),
            array('nome'=>'alam', 'cognome'=>'1BB', 'email'=>'102'),
            array('nome'=>'phpflow', 'cognome'=>'CC', 'email'=>'103') );


    $x = array(
            "draw"            => 1,
            "recordsTotal"    => count($cc),
            "recordsFiltered" => count($cc),
            "data"            => $cc
        );
    echo json_encode($x);

} }

然后,这是che js code

<script type="text/javascript">
function myfunc(){
   $('#example').DataTable( {
        'processing': true,
        'serverSide': true,
        'ajax':{
            type: 'POST',
            url: "<?php echo Cake\Routing\Router::url(
                array(
                   'controller'=>'posts',
                   'action'=>'getdata',
                    '_ext'=>'json',
                   '_full' => true //for full url path
             ));?>",

            success:function(msg){
                console.log(msg);
            },
            error: function(e) {
                    alert("An error occurred: ");
                    console.log(e);
            }
        }
    } );
}

操作已正确发送,但我总是收到一条消息错误,其中,在Google Chrome开发工具中,我看到了一个&#39; null&#39;附在数据之后:

{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"nome":"parvez","cognome":"AA","email":"101"},{"nome":"alam","cognome":"1BB","email":"102"},{"nome":"phpflow","cognome":"CC","email":"103"}]}null

我试着不用json_encode动作响应,在chrome中我看到数据数组后面的东西:

App \ Controller \ PostsController :: getdata() - APP / Controller \ PostsController.php,第147行 Cake \ Controller \ Controller :: invokeAction() - CORE \ src \ Controller \ Controller.php,第440行 Cake \ Http \ ActionDispatcher :: _ invoke() - CORE \ src \ Http \ ActionDispatcher.php,第119行 Cake \ Http \ ActionDispatcher :: dispatch() - CORE \ src \ Http \ ActionDispatcher.php,第93行 Cake \ Routing \ Dispatcher :: dispatch() - CORE \ src \ Routing \ Dispatcher.php,第60行 [主要] - ROOT \ webroot \ index.php,第37行Arraynull

所以,问题来自index.php页面,但为什么它会返回一个null数组呢? 感谢

1 个答案:

答案 0 :(得分:1)

好吧,我认为这段代码坏了,你回复json但是,不要停止渲染器,请看帮助你。

//On controller
$cc = [
'message' = > 'Hello mr.bitdiego'
];
$this->set('data', $cc);
$this->set('_serialize', ['data']);

在你的app控制器上,当找到序列化数据时,这个替换模板和渲染布局到ajax,参见Template / Layout / Ajax.ctp

但是,你为什么要这样做?请参阅CakeBook: Create Restful Resources您不创建控制器的操作,现在您使用资源。 :D请看,促进你的生活。