在我的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.rnrnAlso within the **Manhattan** area!",
"status": "1",
"promoted": "0",
"latitude": "53.6570794",
"longitude": "-1.8277604"
},...
正如您所看到的,这两个JSON对象没有正确地组合在一起。。。我该如何解决这个问题?
使用CakePHP 2.3
解决方案如下:
1( 不要从beforeFilter((函数中回显任何内容——这会破坏单元测试。
2( 在app_controller中创建一个名为$extra_data的受保护变量;
3( 如果您有echo语句,只需将$extra_data设置为$response;
4( 在回显主json的控制器操作中,检查!空($this->extra_data(,如果这是真的,那么将您的主操作响应与额外的数据合并,并将其设置为您的视图,在那里以json形式回显。
尝试json_encode(array_merge($response((;