0

我试图从 cakephp 3.1 控制器函数返回 json。我的问题是,无论我对 _serialize 标志做什么,响应总是缺少视图模板文件。

在蛋糕文档中,它说如果您不需要使用模板来格式化响应,则设置 _serialize 标志。查看 _serialize 上的蛋糕文档

下面是初始化进程的客户端的Javascript

    function save_activity( mod, act, resp ) {

    $.ajax({
            method: 'POST', 
            url: '/activities/saveActivity', 
            data: { 
                'module' : "example1",
                'activity_name' : "example2",
                'response' : "example3"
            },
            dataType: 'json', 
            error: function( xhr, status, error ){
                alert( status + error );
            },
               success: function( data, status,  xhr ){
                   alert( status + data.success );
            }
});
}

处理来自客户端的 json 的控制器代码。

public function saveActivity()
    {
        $user = $this->Auth->user();

        //This line does not seem to do anything
        //$this->request->input('json_decode', 'true');

        //Debugger::log($this->request->data);

        $activityTable = TableRegistry::get('Activities');
        $activity = $activityTable->newEntity();

        $activity->user_id = $user['id'];
        $activity->module = $this->request->data('module');
        $activity->activity_name = $this->request->data('activity_name');
        $activity->response = $this->request->data('response');

        //These lines do not have any effect
        //$this->RequestHandler->renderAs($this, 'json');
        //$this->response->type('application/json');
        //$this->viewBuilder()->layout(null);
        //$this->render(false);

        $msg = '';
        if ($activityTable->save($activity)) {
            $msg = 'Activity Stored';
        } else {
            $msg = 'Activity Not Stored';
        }

        $this->set(['response' => $msg]);

       //comment or uncomment this line and it makes no difference
       //as it still returns a json response about a missing template.
       $this->set('_serialize', true);

    }

包含或删除 _serialize 标志时收到的错误消息。

“模板文件“Pages\json\module1\activity4.ctp”丢失。”

有人对此机制有任何见解吗?我发现的解决方法是包含模板文件......但这意味着我将不得不生成几十个基本上为空的模板文件来处理生成此调用的所有位置。

请问有什么帮助吗?

4

1 回答 1

1

问题原因:- 违反假设。

我的假设是正在执行 saveActivity 方法。虽然现实情况是 AuthComponent 未能允许访问该方法并且正在运行默认处理程序,但正在寻找默认视图模板......并且失败了。

我通过 devTools 查看附加到返回页面中的错误消息的堆栈跟踪发现了这一点。我还应该通过一些简单的跟踪日志调用来验证这个假设。当我注释掉“$this->set('_serialize', true);”时,我已经有了线索。什么都没有改变。

那么简单的解决方案就是在控制器 beforeFilter 中授权该方法:

  public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);

        $this->Auth->allow('saveActivity');
        $this->Auth->allow('getActivity');

        $this->eventManager()->off($this->Csrf);
    }

感谢ndm的帮助。

于 2016-02-06T01:00:37.383 回答