7

问题:有时在我们的 zend 控制器中,我们不希望直接输出脚本,而是希望该脚本的内容。一个示例:当我们需要将视图脚本的结果 html 输出包含在另一种结构(如 JSON 或 XML)中以便在客户端进行处理时。

我在堆栈溢出时在这里找到了结果,但不是那么快,因为它在不同的上下文中。我已经为此苦苦挣扎了 2 天。事实证明这很简单:

    // in our controllers' action method
    $this->_helper->layout()->setLayout('empty');    // disable layout
    $this->_helper->viewRenderer->setNoRender(true); // make sure the script is not being rendered

    // any of your code here
    $html = $this->view->render('projects/climate.phtml');  // return the view script content as a string
    $json = array('html'=>$html, 'initData'=>'my other needed data');
    echo json_encode($json);

我希望这很清楚,并且对某人有用。

4

1 回答 1

9

尝试使用

public myAction () {
    $this->_helper->json(array(
        'html'    => $this->view->render('projects/climate.phtml'),
        'initData'=> 'my other needed data',
    ));
}

Json 动作助手通常会

  • 禁用viewRenderer
  • 禁用布局
  • json_encode数组
于 2010-09-27T20:49:54.597 回答