Cakephp3: How can I return json data?

前端 未结 8 3046
不思量自难忘°
不思量自难忘° 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 10:08

    In the latest version of CakePHP $this->response->type() and $this->response->body() are deprecated.

    Instead you should use $this->response->withType() and $this->response->withStringBody()

    E.g:

    (this was pinched from the accepted answer)

    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 = $this->response
                ->withType('application/json') // Here
                ->withStringBody($resultJ)     // and here
    
            return $this->response;
        }
    }
    

    Relevant Documentation

提交回复
热议问题