CakePHP - How to return string (like JSON) from controller action to Ajax request

后端 未结 4 1299
情书的邮戳
情书的邮戳 2021-01-06 04:58

So I have my JavaScript making an Ajax call to /my_controller/ajax_action but then in the controller I don\'t know what to do to output something back to the Ja

相关标签:
4条回答
  • 2021-01-06 05:17

    do this, have your variables you want to output in an array let's say $data, then pass that array to the view using the $this->set('data', $data); method, then create a view /General/SerializeJson.ctp. In that view file, put <?PHP echo json_encode($data); ?> after that you can use $this->render('/General/SerializeJson'); and it should output the json.

    General code...

    /Controllers/MyController.php

    public class MyController extends AppController
    {
        public function ajaxAction()
        {
            $data = Array(
                "name" => "Saad Imran",
                "age" => 19
            );
            $this->set('data', $data);
            $this->render('/General/SerializeJson/');
        }
    }
    

    /Views/General/SerializeJson.ctp

    <?PHP echo json_encode($data); ?>
    
    0 讨论(0)
  • 2021-01-06 05:19

    AutoRender=false and Return json_encode($code)

    public function returningJsonData($estado_id){
        $this->autoRender = false;
    
        return json_encode($this->ModelBla->find('first',array(
            'conditions'=>array('Bla.bla_child_id'=>$estado_id)
        )));
    }
    
    0 讨论(0)
  • 2021-01-06 05:24

    Easiest way I found was to disable the automatic rendering:

    function ajax_action($data = null) {
        if($this->RequestHandler->isAjax()) {
            $this->autoRender = false;
            //process my data and return it
            return $data;
        } else {    
            $this->Session->setFlash(__('Not an AJAX Query', true));
            $this->redirect(array('action' => 'index'));
        }   
    }
    
    0 讨论(0)
  • 2021-01-06 05:35

    try this:

    within your view folder for the corresponding controller(my_controller) make a folder named json and place a file named index.ctp and within that ctp file write this code:

    <?php echo json_encode($yourVariableNameReturnedFromController); ?>
    

    within your my_controller in index() wrote this code:

    $this->set('yourVariableNameReturnedFromController', $this->YOURMODEL->find('all'));
    

    within your app_controller.php(if not exist you have to made it) write this code

    function beforeFilter(){
      if ($this->RequestHandler->ext == 'json') {
         Configure::write('debug', 0);
      }
    }
    
    0 讨论(0)
提交回复
热议问题