如何用cakePHP执行ajax请求?

I know this should be obvious but I couldn't find anything useful or updated on the internet.

I'm trying to perform a request with ajax that gets a view contents as well as a JS code to execute from cakePHP controller.

The request is:

  $.ajax({
    url: '/alarm/fetchGadgetsComponent',
    type: "POST",
    cache: false,
    dataType: 'json',
    success: function (data) {
       console.log(data);
    }
 });

and the PHP class looks like this:

class AlarmController extends AppController {
    public $uses = false;
    public $components = array('RequestHandler');
    public function index() {

    }


    public function fetchGadgetsComponent()
    {
        if ($this->request->is('Ajax'))
        {
            $this->autoRender = false;
            $this->layout = 'ajax';

            $html = $this->render('ajax\widgetsPanel');
            $js = $this->render('ajax\widgetsPanel.js');

            echo json_encode(array('html' => $html,'js' => $js));
        }
    }
}

First, the first render is just rendering it upon the screen instead into the $html variable. Second, how can I get the js file with a different method? (the render method is obviously not meant for this, as it searches for a .ctp file) and how to I parse them together as a json expression?

Thank you

I know that json_encode is php function that change array and other php variables to valid JSON, so you cannot get content of javascript file and change it to JSON using this method.The cake render method render the ctp files if you want change view prefix use:

class AlarmController extends AppController {
    public $uses = false;
    public $components = array('RequestHandler');
    public function index() {

    }


    public function fetchGadgetsComponent()
    {
        if ($this->request->is('Ajax'))
        {
            $this->autoRender = false;
            $this->layout = 'ajax';

            $html = $this->render('ajax\widgetsPanel');

            $this->ext = '.js';
            $js = $this->render('ajax\widgetsPanel.js');

            echo json_encode(array('html' => $html,'js' => $js));
        }
    }
}

link to source code I think that better method is file_get_content function for js files. Second for perform ajax request better is jsonView

If this .js code is used by widgetsPanel, then this should be referneced from within the ctp file, most probably through js or html helpers of cakePHP, for this set the name of js file as a view variable and use it in ctp file.

then you will not need to call $this->render() two times and a simple echo would be fine to display contents of widgetsPanel, so you will be savin one call to render method and call to json_encode. also change dataType to HTML, dataType JSON is for fetching only lean data not entire html view chunks.