Cakephp3:如何返回json数据?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Cakephp3:如何返回json数据?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在调用cakePHP控制器的ajax调用
$.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');
                    }
                }
            });

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

在AppController中我有这个

$this->loadcomponent('RequestHandler');

启用.

Controller函数如下所示:

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']);
}

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

在这里看到的大多数答案要么过时,要么重载不必要的信息,要么依赖于withBody(),感觉解决方法而不是CakePHP方式.

以下是对我有用的东西:

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

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

@L_360_12@.看起来它不会很快被弃用.

脚本宝典总结

以上是脚本宝典为你收集整理的Cakephp3:如何返回json数据?全部内容,希望文章能够帮你解决Cakephp3:如何返回json数据?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。