Cakephp3: How can I return json data?

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

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

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


        
8条回答
  •  闹比i
    闹比i (楼主)
    2021-02-19 10:07

    Instead of returning the json_encode result, set the response body with that result and return it back.

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

    Edit (credit to @Warren Sergent)

    Since CakePHP 3.4, we should use

    return $this->response->withType("application/json")->withStringBody(json_encode($result));
    

    Instead of :

    $this->response->type('json');
    $this->response->body($resultJ);
    return $this->response;
    

    CakePHP Documentation

提交回复
热议问题