我想在控制器操作中将$this->layout
设置为json
。
在json
布局中,会有一行代码$this->Javascript>object();
,它会解析控制器提供的数据,并输出jSON。
然而,为每个jSON请求创建一个新的视图文件,例如recipe_view
、ingredient_view
并不必要,我只需要一个布局。
有没有一种方法可以完全绕过视图文件,只使用布局,而不出现臭名昭著的Missing View!错误?
@pleasedontbelong的解决方案有效。您还可以为Ajax创建布局和视图。
您的布局可以是这样的:
<?php echo $content_for_layout;?>
然后您可以创建一个类似于以下的 AJAX 视图:
<?php echo $this->Js->object($result);?>
public function savecontent(){
$this->autoRender = false;
$this->set('result', false);
if(!empty($this->data)){
$data = $this->data;
//Do something with your data
//send results to view
$this->set('result', $myNewData);
}
$this->render(null, 'ajax','/ajax/ajax');
}
嗯,应该是这样的:(未经测试)
function action(){
$this->autoLayout = $this->autoRender = false;
// your code
$this->render('/layouts/json');
}
在您的 AppController 中,在类声明后添加此行:
public $viewClass = 'Json';
接下来,在您的 Controller 操作末尾添加此行,包括您想要以 json 格式显示的任何数据:
$this->set(compact(array('dataSet1', 'dataSet2')));
$this->set('_serialize', array('dataSet1', 'dataSet2'));
就是这样!您不需要为此设置视图。即使您已经设置了一个视图,CakePHP 也会忽略它,并只显示您在“_serialize”数组中指定的变量。
在config/routes.php文件中:
Router::parseExtensions('json');
在app_controller.php中:
var $components = array('RequestHandler');
var $helpers = array('Js');
function render($action = null, $layout = null, $file = null) {
switch($this->RequestHandler->ext) {
case 'json':
Configure::write('debug', 0);
return parent::render(null, 'default', '/json');
default:
return parent::render($action, $layout, $file);
}
}
<?php echo $this->Js->object(isset($data) ? $data : array()); ?>
<?php
header('Cache-Control: no-store, no-cache, max-age=0, must-revalidate');
header('Content-Type: application/json');
echo $content_for_layout;
?>
$this->set('data', array('foo' => 'bar'));