CakePHP - 只是布局吗?

4

我想在控制器操作中将$this->layout设置为json

json布局中,会有一行代码$this->Javascript>object();,它会解析控制器提供的数据,并输出jSON。

然而,为每个jSON请求创建一个新的视图文件,例如recipe_viewingredient_view并不必要,我只需要一个布局。

有没有一种方法可以完全绕过视图文件,只使用布局,而不出现臭名昭著的Missing View!错误?

4个回答

3

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

2

嗯,应该是这样的:(未经测试)

function action(){
    $this->autoLayout = $this->autoRender = false;

     // your code

    $this->render('/layouts/json');
}

希望这能帮到您。

2
这在 CakePHP 2.1 中变得非常简单。 在此处查看文档
  1. 在您的 AppController 中,在类声明后添加此行:

    public $viewClass = 'Json';

  2. 接下来,在您的 Controller 操作末尾添加此行,包括您想要以 json 格式显示的任何数据:

    $this->set(compact(array('dataSet1', 'dataSet2')));

    $this->set('_serialize', array('dataSet1', 'dataSet2'));

就是这样!您不需要为此设置视图。即使您已经设置了一个视图,CakePHP 也会忽略它,并只显示您在“_serialize”数组中指定的变量。


2

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

在 views/json.ctp 中:
<?php echo $this->Js->object(isset($data) ? $data : array()); ?>

在views/layouts/json/default.ctp文件中:
<?php
header('Cache-Control: no-store, no-cache, max-age=0, must-revalidate');
header('Content-Type: application/json');
echo $content_for_layout;
?>

在控制器操作中,您希望输出JSON:
$this->set('data', array('foo' => 'bar'));

现在,每次调用带有 .json 扩展名的操作(www.example.com/posts/view/12.json),都会输出一个 JSON 对象,而无需在每个操作中调用渲染函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接