Cakephp3:如何返回json数据?

前端之家收集整理的这篇文章主要介绍了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');
                    }
                }
            });

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

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

在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');

More info on RequestHandler.看起来它不会很快被弃用.

原文链接:https://www.f2er.com/php/135701.html

猜你在找的PHP相关文章