2013-10-18 108 views
2

我知道这应该是显而易见的,但我找不到任何有用或在互联网上更新。如何用cakePHP执行ajax请求?

我试图执行一个请求与AJAX获取视图内容以及从CakePHP控制器执行的JS代码。

请求为:

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

和PHP类看起来是这样的:

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

首先,第一渲染只是渲染它在屏幕上,而不是到$html变量。 其次,我如何用不同的方法获取js文件? (渲染方法显然不是这个意思,因为它搜索.ctp文件) 以及如何将它们解析为一个json表达式?

谢谢

+0

你为什么试图在json中发送JavaScript文件的内容?无论你想要做什么,我怀疑最好采取不同的方式。但是,如果绝对必要,则可以将JavaScript文件的内容放在.ctp文件中,然后使用$ this-> render()。 – Kai

回答

0

我知道,json_encode是PHP函数,改变阵列和其它PHP变量到有效的JSON,所以你不能得到JavaScript文件的内容,并使用该method.The蛋糕渲染方法使其改变为JSON在CTP文件,如果你想改变视图前缀使用:

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 我认为,更好的方法是对js文件file_get_content功能。 其次为更好的执行Ajax请求jsonView

0

如果.js文件代码由widgetsPanel,那么这应该从CTP文件内referneced,最有可能通过CakePHP的JS的或HTML辅助,这集的名称js文件作为视图变量并在ctp文件中使用它。

那么你不需要调用$ this-> render()两次,并且一个简单的echo可以很好地显示widgetsPanel的内容,所以你将会喜欢一个调用render方法和调用json_encode的方法。 也将dataType更改为HTML,dataType JSON用于只读取精简数据而不是整个html视图块。