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

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

问题描述

我正在对cakePhp控制器进行ajax发布:

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:

控制器动作只能返回Cake \ Network \ Response或为null.

Controller actions can only return Cake\Network\Response or null.

在AppController中,我有这个

Within the AppController I have this

$this->loadComponent('RequestHandler');

已启用.

Controller函数如下所示:

the Controller function looks like this:

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(),这感觉像是变通解决方案,而不是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.

以下是对我有用的:

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

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

有关RequestHandler的详细信息.看来它不会很快被弃用.

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

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

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