Cakephp3: How can I return json data?

前端 未结 8 3043
不思量自难忘°
不思量自难忘° 2021-02-19 09:39

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

$.ajax({
                type: \"POST\",
                url: \'locations/add\',
                data: {
           


        
8条回答
  •  花落未央
    2021-02-19 09:51

    there are few things to return JSON response:

    1. load RequestHandler component
    2. set rendering mode as json
    3. set content type
    4. set required data
    5. define _serialize value

    for example you can move first 3 steps to some method in parent controller class:

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

    later in your controller you should call that method, and set required data;

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

    also it looks like you should also check for request->is('ajax); I'm not sure about returning json in case of GET request, so setJsonResponse method is called within if-post block;

    in your ajax-call success handler you should check result field value:

    success: function (response) {
                 if(response.result == "success") {
                     console.log('success');
                 } 
                 else if(response.result === "error") {
                        console.log('error');
                 }
             }
    

提交回复
热议问题