[英]How to render a view in modal window using ajax in ZF2?
我尝试在 Zend Framework 2 中使用 ajax 调用在模态窗口中呈现具有专用视图的动作。
这是我的控制器操作:
public function myAction()
{
$htmlViewPart = new ViewModel();
$htmlViewPart->setTemplate('path/to/my/view')
->setTerminal(true)
->setVariables(['arrayVar' => ['a', 'b', 'c']]);
return $htmlViewPart;
}
风景 :
<?php
foreach($arrayVar as $k => $v)
{
echo $k . ':' . $v . '<br>';
}
js:
$(".my-modal-link").click(function() {
$('#myModal .modal-body').load($(this).data('/url/to/my/action'));
});
这不是诀窍。 我也尝试过使用 JSON 模型:
public function myAction()
{
$htmlViewPart = new ViewModel();
$htmlViewPart->setTemplate('path/to/my/view')
->setTerminal(true)
->setVariables(['arrayVar' => ['a', 'b', 'c']]);
$htmlOutput = $this->getServiceLocator()->get('viewrenderer')->render($htmlViewPart);
$jsonModel = new JsonModel();
$jsonModel->setVariables(['html' => $htmlOutput]);
return $jsonModel;
}
但模态中的最终渲染类似于:
{"html":"0:a\u003Cbr\u003E1:b\u003Cbr\u003E2:c\u003Cbr\u003E"}
知道如何实现这一目标吗?
您所需要的只是使用setTerminal()
禁用布局并从控制器返回正确的模型以在您的模式中呈现 HTML 输出。
在您的情况下,您必须返回一个ViewModel实例。 所以,你的第一种方法是正确的。 这应该有效:
$htmlViewPart = new ViewModel();
$htmlViewPart->setTemplate('path/to/my/view')
->setTerminal(true)
->setVariables(['arrayVar' => ['a', 'b', 'c']]);
return $htmlViewPart;
第二种情况是; 您正在尝试使用 HTML 输出作为 json 数据。 尝试更改类似于此的 ajax 加载机制:
$(".my-modal-link").click(function() {
$.get("/url/to/my/action", function(data) {
$('#myModal .modal-body').html(data);
});
});
这会将渲染的输出(没有布局)附加到模态的主体中。 您可能还想为JsonModel场景阅读这篇文章。
希望能帮助到你。
我找到了解决方案。
只需创建一个返回内容的空布局。
// Application/view/layout/ajax.phtml
<?php
echo $this->content;
并在动作视图中设置此模板
<?php
$this->layout()->setTemplate('layout/ajax');
它现在适用于 Jquery $.load() / ViewModel 策略
有同样的问题,这有效...
$.get("<?php echo $this->url('your url'); ?>", function(data)
{
console.log(data);
$('#myModal .modal-body').html(data);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.