【问题标题】:CakePHP add action returning jsonCakePHP 添加动作返回 json
【发布时间】:2015-12-02 13:56:18
【问题描述】:

我有一些关于如何改进“控制器”中的“添加操作”(方法)的问题:

1st:我仅在发布请求时才使用add 操作。对吗?

第二次:action 没有视图 ($this->autoRender = false;)。对吗?

3rd: 我将一个响应 .json 文件设置为这个 action,但我没有更改路由 .json 文件的路由(访问 localhost 时该文件将返回: 8765/用户/添加)。对吗?

4th:我正在使用Enums(handmade) 来存储将返回给用户的消息。对吗?

5th:我正在使用一个对象来存储消息的字段(将返回给用户),该对象将被序列化并返回如下:

$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"}

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    1st:我仅在发布请求时才使用添加操作。对吗?

    是的

    2nd:这个动作没有视图($this->autoRender = false;)。对吗?

    不是真的。您应该使用 JsonView 而不是将 json 字符串设置为控制器中的响应正文。

    3rd:我为此操作设置了一个响应 .json 文件,但我没有更改路由 .json 文件的路由(访问 localhost:8765/users/add 时将返回该文件)。对吗?

    没关系。不需要使用以非 .json 结尾的 URL。但是您应该将请求中的Accept 标头设置为application/json

    4th:我正在使用 Enums(handmade) 来存储将返回给用户的消息。对吗?

    没关系。你可以看看这个enum 插件。

    5th:我正在使用一个对象来存储消息的字段(将返回给用户),该对象将被序列化并返回如下:

    如上所述最好使用JsonView。

    【讨论】:

    • 我用正确的代码和新问题更新了我的答案。
    • $this->set('_serialize', ['response']); 更改为$this->set('_serialize', 'response');
    猜你喜欢
    • 2017-03-29
    • 1970-01-01
    • 2016-03-31
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2023-01-13
    • 2017-03-31
    相关资源
    最近更新 更多