繁体   English   中英

如何用cakePHP执行ajax请求?

[英]how to perform an ajax request with cakePHP?

我知道这应该是显而易见的,但我在互联网上找不到任何有用或更新的东西。

我正在尝试使用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表达式一起解析?

谢谢

我知道json_encode是php函数,它将数组和其他php变量更改为有效的JSON,因此你无法获取javascript文件的内容并使用此方法将其更改为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));
        }
    }
}

链接到源代码我认为更好的方法是js文件的file_get_content函数。 第二个执行ajax请求更好的是jsonView

如果这个.js代码被widgetsPanel使用,那么这应该从ctp文件中引用,最有可能是通过cakePHP的js或html帮助程序引用,为此设置js文件的名称作为视图变量并在ctp文件中使用它。

然后你不需要调用$ this-> render()两次,一个简单的echo就可以显示widgetsPanel的内容了,所以你可以调用render方法并调用json_encode。 也将dataType更改为HTML,dataType JSON仅用于获取精益数据,而不是整个html视图块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM