Cakephp3:如何返回 json 数据? [英] Cakephp3: How can I return json data?

查看:16
本文介绍了Cakephp3:如何返回 json 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对 cakePhp 控制器进行 ajax post 调用:

I am having a ajax post call to a cakePhp Controller:

$.ajax({
                type: "POST",
                url: 'locations/add',
                data: {
                  abbreviation: $(jqInputs[0]).val(),
                  description: $(jqInputs[1]).val()
                },
                success: function (response) {
                    if(response.status === "success") {
                        // do something with response.message or whatever other data on success
                        console.log('success');
                    } else if(response.status === "error") {
                        // do something with response.message or whatever other data on error
                        console.log('error');
                    }
                }
            });

当我尝试这个时,我收到以下错误消息:

When I try this I get the following error message:

控制器动作只能返回 CakeNetworkResponse 或 null.

Controller actions can only return CakeNetworkResponse or null.

在 AppController 中我有这个

Within the AppController I have this

$this->loadComponent('RequestHandler');

启用.

控制器函数如下所示:

public function add()
{
    $this->autoRender = false; // avoid to render view

    $location = $this->Locations->newEntity();
    if ($this->request->is('post')) {
        $location = $this->Locations->patchEntity($location, $this->request->data);
        if ($this->Locations->save($location)) {
            //$this->Flash->success(__('The location has been saved.'));
            //return $this->redirect(['action' => 'index']);
            return json_encode(array('result' => 'success'));
        } else {
            //$this->Flash->error(__('The location could not be saved. Please, try again.'));
            return json_encode(array('result' => 'error'));
        }
    }
    $this->set(compact('location'));
    $this->set('_serialize', ['location']);
}

我在这里想念什么?是否需要其他设置?

What do I miss here? Is there any additional settings needed?

推荐答案

我在这里看到的大多数答案要么过时,过多的不必要信息,要么依赖 withBody(),感觉是变通的-ish 而不是 CakePHP 方式.

Most answers I've seen here are either outdated, overloaded with unnecessary information, or rely on withBody(), which feels workaround-ish and not a CakePHP way.

以下是对我有用的方法:

Here's what worked for me instead:

$my_results = ['foo'=>'bar'];

$this->set([
    'my_response' => $my_results,
    '_serialize' => 'my_response',
]);
$this->RequestHandler->renderAs($this, 'json');

关于的更多信息请求处理程序.似乎它不会很快被弃用.

More info on RequestHandler. Seemingly it's not getting deprecated anytime soon.

更新:CakePHP 4

$this->set(['my_response' => $my_results]);
$this->viewBuilder()->setOption('serialize', true);
$this->RequestHandler->renderAs($this, 'json');

更多信息

这篇关于Cakephp3:如何返回 json 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆