Cakephp3: How can I return json data?

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

    Most answers I've seen here are either outdated, overloaded with unnecessary information, or rely on withBody(), which feels workaround-ish and not a CakePHP way.

    Here's what worked for me instead:

    $my_results = ['foo'=>'bar'];
    
    $this->set([
        'my_response' => $my_results,
        '_serialize' => 'my_response',
    ]);
    $this->RequestHandler->renderAs($this, 'json');
    

    More info on RequestHandler. Seemingly it's not getting deprecated anytime soon.

    UPDATE: CakePHP 4

    $this->set(['my_response' => $my_results]);
    $this->viewBuilder()->setOption('serialize', true);
    $this->RequestHandler->renderAs($this, 'json');
    

    More info

提交回复
热议问题