我试图从 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”丢失。”
有人对此机制有任何见解吗?我发现的解决方法是包含模板文件......但这意味着我将不得不生成几十个基本上为空的模板文件来处理生成此调用的所有位置。
请问有什么帮助吗?