发送 AJAX 响应时,如何使 Zend Framework 不呈现视图/布局?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1498692/
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 do you make Zend Framework NOT render a view/layout when sending an AJAX response?
提问by Don Jones
Zend's documentation isn't really clear on this.
Zend 的文档对此并不十分清楚。
The problem is that, by default, Zend automatically renders a view at the end of each controller action. If you're using a layout - and why wouldn't you? - it also renders that. This is fine for normal Web pages, but when you're sending an AJAX response you don't want all that. How do you prevent Zend from auto-rendering on an action-by-action basis?
问题是,默认情况下,Zend 会在每个控制器操作结束时自动呈现一个视图。如果您正在使用布局 - 为什么不呢?- 它也呈现。这对于普通 Web 页面来说很好,但是当您发送 AJAX 响应时,您不想要所有这些。您如何防止 Zend 在逐个操作的基础上自动呈现?
回答by Don Jones
Call this code from within whatever Action(s) is/are going to be sending AJAX responses:
从将要发送 AJAX 响应的任何操作中调用此代码:
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(TRUE);
This disables the Layout engine for that action, and it turns off automatic view rendering for that action. You can then just "echo" whatever you want your AJAX output to be, without worrying about the normal view/layout stuff getting sent along for the ride.
这将禁用该操作的布局引擎,并关闭该操作的自动视图渲染。然后,您可以“回显”您希望 AJAX 输出的任何内容,而不必担心正常的视图/布局内容会被发送出去。
回答by Valeriy Selitskiy
If your AJAX is returning JSON you can use JSON action helper:
如果您的 AJAX 返回 JSON,您可以使用 JSON 操作助手:
$this->_helper->json($data);
This helper will json_encodeyour $data, output it with JSON headers and die at last, so we getting clean JSON returned from action without layout and view rendering.
这个助手将json_encode你的 $data,用 JSON 标头输出它,最后死掉,所以我们从动作返回干净的 JSON,没有布局和视图渲染。
f.e. I am using this construction in action beginning to avoid multiple ACL checks for different actions just-for-ajax
fe 我在行动中使用这个构造开始避免针对不同操作的多个 ACL 检查 just-for-ajax
public function photosAction() {
if ($this->getRequest()->getQuery('ajax') == 1 || $this->getRequest()->isXmlHttpRequest()) {
$params = $this->getRequest()->getParams();
$result = false;
switch ($params['act']) {
case 'deleteImage':
//deleting something
...
$result = true; //ok
break;
default :
$result = array('error' => 'Invalid action: ' . $params['act']);
break;
}
$this->_helper->json($result);
}
// regular action code here
...
}
回答by midan888
Or you could simply put die() function at the end of the action
或者你可以简单地将 die() 函数放在动作的末尾
public function someAction()
{
echo json_encode($data);
die();
}

