在我的CakePHP应用程序中,我在beforeFilter中执行一些操作,以传递有关用户或身份验证等的响应的额外JSON数据。
例如:
public function beforeFilter()
{
$this->Auth->allow(array('index'));
// If the request is either JSON or XML
if ( $this->params['ext'] == 'json' || $this->params['ext'] == 'xml' )
{
if( $this->Auth->user() )
{
// User is logged in so send userdata and usual response will also be passed
$response = array('meta' =>
array(
'auth' => true,
'user_id' => $this->Auth->user('id')
)
);
echo json_encode($response);
}
else
{
$requiresAuth = !in_array($this->params['action'], $this->Auth->allowedActions);
if ($requiresAuth)
{
$response = array('meta' =>
array(
'auth' => false
)
);
echo json_encode($response);
exit; // exit so no other responses go through
}
else
{
// Send JSON usual response
$response = array('meta' =>
array(
'auth' => false
)
);
echo json_encode($response);
}
}
}
parent::beforeFilter();
}
这用于为移动应用构建我的RESTful API。这里的问题是完整返回的JSON如下所示:
{
"meta": {
"auth": false,
}
} {
"posts": [{
"Post": {
"id": "136",
"user_id": "8",
"datetime": "2012-09-11 15:49:52",
"modified": "2012-09-16 15:31:38",
"title": "Where is good to eat in New York?",
"slug": "Where_is_good_to_eat_in_New_York",
"content": "Preferably italian or mexican and with a good atmosphere.\r\n\r\nAlso within the **Manhattan** area!",
"status": "1",
"promoted": "0",
"latitude": "53.6570794",
"longitude": "-1.8277604"
},...
正如您所看到的,两个JSON对象没有正确组合在一起......我该如何解决这个问题?
使用CakePHP 2.3
答案 0 :(得分:0)
解决方案如下:
1)不要回复beforeFilter()函数中的任何内容 - 它会破坏单元测试。
2)在app_controller中创建一个名为$ extra_data;
的受保护变量3)你有echo语句,只需将$ extra_data设置为$ response;
4)在你的控制器动作中回显你的主json,检查!空($ this-> extra_data)如果这是真的,请将您的主动作响应与额外数据合并,并将其设置为您的视图以在那里作为json回显。