簡體   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