Zend框架2:Ajax调用自动禁用布局 [英] Zend Framework 2: Auto disable layout for ajax calls
问题描述
一个Ajax请求我的控制器操作之一目前返回完整的HTML页面。
An AJAX request to one of my controller actions currently returns the full page HTML.
我只希望它返回的HTML(.phtml作为内容),针对该特殊操作。
I only want it to return the HTML (.phtml contents) for that particular action.
以下code不佳手动禁用布局的具体行动解决问题
The following code poorly solves the problem by manually disabling the layout for the particular action:
$viewModel = new ViewModel();
$viewModel->setTerminal(true);
return $viewModel;
我怎样才能让我的应用程序自动禁用布局,检测一个AJAX请求时?我是否需要写这个自定义的策略?如何做到这一点的任何建议是多AP preciated。
How can I make my application automatically disable the layout when an AJAX request is detected? Do I need to write a custom strategy for this? Any advice on how to do this is much appreciated.
此外,我已经试过以下code。在我的应用程序Module.php - 这是正确检测AJAX但setTerminal()不禁止的布局
Additionally, I've tried the following code in my app Module.php - it is detecting AJAX correctly but the setTerminal() is not disabling the layout.
public function onBootstrap(EventInterface $e)
{
$application = $e->getApplication();
$application->getEventManager()->attach('route', array($this, 'setLayout'), 100);
$this->setApplication($application);
$this->initPhpSettings($e);
$this->initSession($e);
$this->initTranslator($e);
$this->initAppDi($e);
}
public function setLayout(EventInterface $e)
{
$request = $e->getRequest();
$server = $request->getServer();
if ($request->isXmlHttpRequest()) {
$view_model = $e->getViewModel();
$view_model->setTerminal(true);
}
}
思考?
推荐答案
事实上,最好的办法是写另一个策略。有一个JsonStrategy它可以自动检测接收头,自动返回JSON格式的,但与阿贾克斯,呼吁fullpages,有它的好,它并不会自动做的事情,因为你可能希望得到一个完整的页面。上面提到的解决方案,您提到的将是快速的路要走。
Indeed the best thing would be to write another Strategy. There is a JsonStrategy which can auto-detect the accept header to automatically return Json-Format, but as with Ajax-Calls for fullpages, there it's good that it doesn't automatically do things, because you MAY want to get a full page. Above mentioned solution you mentioned would be the quick way to go.
当去为全速,你只能有一个附加行。它总是从你的控制器内返回完全合格的ViewModels最佳实践。像:
When going for full speed, you'd only have one additional line. It's a best practice to always return fully qualified ViewModels from within your controller. Like:
public function indexAction()
{
$request = $this->getRequest();
$viewModel = new ViewModel();
$viewModel->setTemplate('module/controller/action');
$viewModel->setTerminal($request->isXmlHttpRequest());
return $viewModel->setVariables(array(
//list of vars
));
}
这篇关于Zend框架2:Ajax调用自动禁用布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!