php 如何在 JSON 响应中呈现 ZF2 视图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12451399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to render ZF2 view within JSON response?
提问by webjawns.com
So far, I have figured out how to return a typical JSON response in Zend Framework 2. First, I added the ViewJsonStrategyto the strategiessection of the view_managerconfiguration. Then, instead of returning a ViewModelinstance from the controller action, I return a JsonModelinstance with all my variables set.
到目前为止,我已经想通了如何返回Zend框架2.首先一个典型的JSON响应,我加入ViewJsonStrategy到strategies了部分view_manager配置。然后,我没有ViewModel从控制器操作返回一个实例,而是返回一个JsonModel设置了所有变量的实例。
Now that I've figured that piece out, I need to understand how to render a view and return it within that JSON response. In ZF1, I was able to use $this->view->render($scriptName), which returned the HTML as a string. In ZF2, the Zend\View\View::render(...)method returns void.
现在我已经弄清楚了那部分,我需要了解如何呈现视图并在该 JSON 响应中返回它。在 ZF1 中,我能够使用$this->view->render($scriptName),它将 HTML 作为字符串返回。在 ZF2 中,该Zend\View\View::render(...)方法返回void。
So... how can I render an HTML view script and return it in a JSON response in one request?
那么...如何呈现 HTML 视图脚本并在一个请求中以 JSON 响应的形式返回它?
This is what I have right now:
这就是我现在所拥有的:
if ($this->getRequest()->isXmlHttpRequest()) {
$jsonModel = new JsonModel(...);
/* @todo Render HTML script into `$html` variable, and add to `JsonModel` */
return $jsonModel;
} else {
return new ViewModel(...);
}
回答by Sam
OK, i think i finally understood what you're doing. I've found a solution that i think matches your criteria. Though i am sure that there is room for improvement, as there's some nasty handwork to be done...
好的,我想我终于明白你在做什么了。我找到了一个我认为符合您标准的解决方案。虽然我确信还有改进的余地,因为有一些讨厌的手工要做......
public function indexAction()
{
if (!$this->getRequest()->isXmlHttpRequest()) {
return array();
}
$htmlViewPart = new ViewModel();
$htmlViewPart->setTerminal(true)
->setTemplate('module/controller/action')
->setVariables(array(
'key' => 'value'
));
$htmlOutput = $this->getServiceLocator()
->get('viewrenderer')
->render($htmlViewPart);
$jsonModel = new JsonModel();
$jsonModel->setVariables(array(
'html' => $htmlOutput,
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1,2,3,4,5,6)
));
return $jsonModel;
}
As you can see, the templateMap i create is ... nasty ... it's annoying and i'm sure it can be improved by quite a bit. It's a working solution but just not a clean one. Maybe somehow one would be able to grab the, probably already instantiated, default PhpRenderer from the ServiceLocator with it's template- and path-mapping and then it should be cleaner.
正如您所看到的,我创建的 templateMap 是......讨厌......它很烦人,我相信它可以得到很大的改进。这是一个有效的解决方案,但不是一个干净的解决方案。也许以某种方式可以从 ServiceLocator 获取可能已经实例化的默认 PhpRenderer 及其模板和路径映射,然后它应该更干净。
Thanks to the comment ot @DrBeza the work needed to be done could be reduced by a fair amount. Now, as I'd initially wanted, we will grab the viewrenderer with all the template mapping intact and simply render the ViewModel directly. The only important factor is that you need to specify the fully qualified template to render (e.g.: "$module/$controller/$action")
感谢@DrBeza 的评论,需要完成的工作可以减少相当数量。现在,正如我最初想要的那样,我们将获取带有完整模板映射的 viewrenderer,然后直接渲染 ViewModel。唯一重要的因素是您需要指定要呈现的完全限定模板(例如:“$module/$controller/$action”)
I hope this will get you started though ;)
我希望这会让你开始;)
PS: Response looks like this:
PS:响应如下:
Object:
html: "<h1>Hello World</h1>"
jsonArray: Array[6]
jsonVar1: "jsonVal2"
回答by Maksym Kalin
You can use more easy way to render view for your JSON response.
您可以使用更简单的方法为您的 JSON 响应呈现视图。
public function indexAction() {
$partial = $this->getServiceLocator()->get('viewhelpermanager')->get('partial');
$data = array(
'html' => $partial('MyModule/MyPartView.phtml', array("key" => "value")),
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1, 2, 3, 4, 5, 6));
$isAjax = $this->getRequest()->isXmlHttpRequest());
return isAjax?new JsonModel($data):new ViewModel($data);
}
Please note before use JsonModel class you need to config View Manager in module.config.phpfile of your module.
请注意,在使用 JsonModel 类之前,您需要在模块的module.config.php文件中配置视图管理器。
'view_manager' => array(
.................
'strategies' => array(
'ViewJsonStrategy',
),
.................
),
it is work for me and hope it help you.
这对我有用,希望对你有帮助。
回答by halanson
In ZF 3 you can achieve the same result with this code
在 ZF 3 中,您可以使用此代码获得相同的结果
MyControllerFactory.php
我的控制器工厂.php
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$renderer = $container->get('ViewRenderer');
return new MyController(
$renderer
);
}
MyController.php
我的控制器.php
private $renderer;
public function __construct($renderer) {
$this->renderer = $renderer;
}
public function indexAction() {
$htmlViewPart = new ViewModel();
$htmlViewPart
->setTerminal(true)
->setTemplate('module/controller/action')
->setVariables(array('key' => 'value'));
$htmlOutput = $this->renderer->render($htmlViewPart);
$json = \Zend\Json\Json::encode(
array(
'html' => $htmlOutput,
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1, 2, 3, 4, 5, 6)
)
);
$response = $this->getResponse();
$response->setContent($json);
$response->getHeaders()->addHeaders(array(
'Content-Type' => 'application/json',
));
return $this->response;
}
回答by Andrey Gache
As usual framework developer mess thing about AJAX following the rule why simple if might be complex Here is simple solution in controller script
像往常一样,框架开发人员将 AJAX 弄得一团糟,遵循规则为什么简单如果可能很复杂这是控制器脚本中的简单解决方案
public function checkloginAction()
{
// some hosts need to this some not
//header ("Content-type: application/json"); // this work
// prepare json aray ....
$arr = $array("some" => .....);
echo json_encode($arr); // this works
exit;
}
This works in ZF1 and ZF2 as well No need of view scrpt at all
这也适用于 ZF1 和 ZF2 根本不需要查看 scrpt
If you use advise of ZF2 creator
如果您使用 ZF2 creator 的建议
use Zend\View\Model\JsonModel;
....
$result = new JsonModel($arr);
return $result;
AJAX got null as response at least in zf 2.0.0
至少在 zf 2.0.0 中,AJAX 作为响应得到了 null

