我知道这应该是显而易见的,但我在互联网上找不到任何有用的或更新的内容。
我正在尝试使用 ajax 执行请求以获取 View 内容以及要从 cakePHP Controller 执行的 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 变量更改为有效 JSON 的 php 函数,因此您无法使用此方法获取 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));
}
}
}
link to source code
我认为更好的方法是 js 文件的 file_get_content
函数。
第二个更好地执行 ajax 请求的是 jsonView
关于javascript - 如何使用 cakePHP 执行 ajax 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19452623/