我尝试在模态窗口中使用专用视图在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);
});