在我的 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