Cakephp3:如何返回json数据?

use*_*112 12 json cakephp

我正在调用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');
                    }
                }
            });
Run Code Online (Sandbox Code Playgroud)

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

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

在AppController中我有这个

$this->loadComponent('RequestHandler');
Run Code Online (Sandbox Code Playgroud)

启用.

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']);
}
Run Code Online (Sandbox Code Playgroud)

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

bet*_*per 18

而不是返回json_encode结果,设置具有该结果的响应主体并将其返回.

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']);
            $resultJ = json_encode(array('result' => 'success'));
            $this->response->type('json');
            $this->response->body($resultJ);
            return $this->response;
        } else {
            //$this->Flash->error(__('The location could not be saved. Please, try again.'));
            $resultJ = json_encode(array('result' => 'error', 'errors' => $location->errors()));

            $this->response->type('json');
            $this->response->body($resultJ);
            return $this->response;
        }
    }
    $this->set(compact('location'));
    $this->set('_serialize', ['location']);
}
Run Code Online (Sandbox Code Playgroud)

编辑(归功于@Warren Sergent)

从CakePHP 3.4开始,我们应该使用

return $this->response->withType("application/json")->withStringBody(json_encode($result));
Run Code Online (Sandbox Code Playgroud)

代替 :

$this->response->type('json');
$this->response->body($resultJ);
return $this->response;
Run Code Online (Sandbox Code Playgroud)

CakePHP文档

  • 值得注意的是,自CakePHP 3.4以来,这已不再有效.您应该使用`return $ this-> response-> withType("application/json") - > withStringBody(json_encode($ result));`允许将字符串传递给不可变响应. (2认同)

aex*_*exl 13

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

以下是对我有用的东西:

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

$this->set([
    'my_response' => $my_results,
    '_serialize' => 'my_response',
]);
$this->RequestHandler->renderAs($this, 'json');
Run Code Online (Sandbox Code Playgroud)

更多信息RequestHandler.看起来它不会很快被弃用.


ter*_*ran 7

JSON回复的东西很少:

  1. 加载RequestHandler组件
  2. 将渲染模式设置为 json
  3. 设置内容类型
  4. 设置所需数据
  5. 定义_serialize价值

例如,您可以将前3个步骤移动到父控制器类中的某个方法:

protected function setJsonResponse(){
    $this->loadComponent('RequestHandler');
    $this->RequestHandler->renderAs($this, 'json');
    $this->response->type('application/json');
}
Run Code Online (Sandbox Code Playgroud)

稍后在您的控制器中,您应该调用该方法,并设置所需的数据;

if ($this->request->is('post')) {
    $location = $this->Locations->patchEntity($location, $this->request->data);

    $success = $this->Locations->save($location);

    $result = [ 'result' => $success ? 'success' : 'error' ];

    $this->setJsonResponse();
    $this->set(['result' => $result, '_serialize' => 'result']);
}
Run Code Online (Sandbox Code Playgroud)

看起来你也应该检查request->is('ajax); 我不确定jsonGET请求的情况下返回,因此setJsonResponseif-post块内调用方法;

在你的ajax-call成功处理程序中,你应该检查result字段值:

success: function (response) {
             if(response.result == "success") {
                 console.log('success');
             } 
             else if(response.result === "error") {
                    console.log('error');
             }
         }
Run Code Online (Sandbox Code Playgroud)