我有我如何能改善這種「加行動」的一些問題(方法):我使用的是add
動作只有在POST請求:CakePHP的添加操作在「控制器」返回JSON
1日。這是正確的 ?
第2張:這action
沒有意見($this->autoRender = false;
)。這是正確的 ?
3:我設置以.json文件針對這一action
但我沒有航線上改變路由以.json文件(該文件將被返回的時候訪問本地主機:8765 /用戶/加)。這是正確的 ?
4th:我使用Enums
(手工製作)存儲將返回給用戶的消息。這是正確的 ?
第五:我使用的對象來存儲消息的字段(這將返回給用戶)時,該對象將被序列化,並返回這樣的:
$this->response->body(json_encode($response)); // It's correct ?
控制器代碼:
public function add()
{
$this->autoRender = false;
$this->response->type('json');
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Auth->setUser($user->toArray());
$response = new ResponseMessage();
$response->code = CodeEnum::USER_ADDED;
$response->name = NameEnum::USER_ADDED;
$response->type = TypeMessageEnum::SUCCESS;
$this->response->body(json_encode($response));
} else {
$response = new ResponseMessage();
$response->code = CodeEnum::USER_NOT_ADDED;
$response->name = NameEnum::USER_NOT_ADDED;
$response->type = TypeMessageEnum::ERROR;
$this->response->body(json_encode($response));
}
}
}
[更新]
我把我的這個控制器上:
$this->set('response', $response);
$this->set('_serialize', ['response']);
但返回此JSON:
{response: {code: 1, name: "Login efetuado com sucesso.", message: null, type: "Sucesso"}}
,但只能被退回:
{code: 1, name: "Login efetuado com sucesso.", message: null, type: "Sucesso"}
我用正確的代碼和新問題更新我的答案。 – Ricardo
更改'$ this-> set('_ serialize',['response']); '到'$ this-> set('_ serialize','response'); ' – ADmad