【发布时间】:2016-02-05 01:13:23
【问题描述】:
我试图从 cakephp 3.1 控制器函数返回 json。我的问题是,无论我对 _serialize 标志做什么,响应总是缺少视图模板文件。
在 cake docs 中,如果您不需要使用模板来格式化响应,请设置 _serialize 标志。 Cake Docs on View _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”丢失。”
有人对此机制有任何见解吗?我发现的解决方法是包含模板文件......但这意味着我将不得不生成几十个基本上为空的模板文件来处理生成此调用的所有位置。
有什么帮助吗?
【问题讨论】:
-
URL/操作似乎不适合错误消息...它适合
/pages/module1/activity4。所以要么你在做一些奇怪的路由,要么你没有展示完整的画面。 -
当我尝试调试系统时,我刚刚在 ajax 数据字段中有示例错误消息。我正在使用通用 ajax 处理程序和通用控制器操作,而不是为许多模块和许多活动复制所有功能。除了 _serialize 标志不会像我理解的那样关闭视图模板之外,这一切都有效。我只想从通用控制器操作生成通用 json 响应,而不是让它通过视图层,这将导致许多重复的处理程序文件都在做同样的事情..
-
感谢 ndm 提供的线索。不是 _serialize 键不起作用……只是“saveActivity”控制器操作甚至没有被执行。 AuthController 失败存在问题,并且呼叫正在通过不同的呼叫路径重定向。进步。它总是让我得到未经证实的假设。
标签: json cakephp cakephp-3.x