Zend框架:如何处理异常的Ajax请求? [英] Zend Framework: How to handle exceptions in Ajax requests?

查看:112
本文介绍了Zend框架:如何处理异常的Ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当一个异常被抛出,错误控制器会命令并显示错误页面与普通常见的页眉和页脚。

Normally when an exception is thrown, Error controller takes command and displays error page with regular common header and footer.

此行​​为是不想要的Ajax请求。因为在错误的情况下,整个HTML页面发送过来。而在情况下,我直接装在一个div HTTP响应的内容,这更是有害的。

This behavior is not wanted in Ajax request. Because in case of error, whole html page is sent over. And in cases where I'm directly loading the content of http response in a div, this is even more unwanted.

相反的情况下​​,Ajax请求,我只想得到抛出异常'实际的错误。

Instead in case of Ajax request, I just want to receive 'the actual error' thrown by exception.

我怎样才能做到这一点?

How can I do this?

我想,人们肮脏的方式可以是:设置Ajax请求和处理相应的变种。没有一个很好的解决方案。

I think, one dirty way could be: set a var in ajax request and process accordingly. Not a good solution.

推荐答案

如果您使用了 ContextSwitch正是 ajaxContext 动作助手为en code你的错误(可能关闭 autoJsonSerialization )你可以只通过错误早在JSON / XML对象。

if you use either the contextSwitch or ajaxContext action helpers to encode your error (possibly turning off autoJsonSerialization) you could just pass the errors back as JSON / XML objects.

<一个href="http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch" rel="nofollow">http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch

class Error_Controller extends Zend_Controller{
    public function errorAction(){
        $contextSwitch = $this->_helper->getHelper('contextSwitch');
        $contextSwitch->addActionContext($this->getRequest()->getActionName(),'json')
            ->initContext();
        $errors = $this->_getParam('error_handler');
        $this->view->exception = $errors->exception;
    }
}

从那里,你要么通过一个格式= json的参数,每个AJAX请求或设置一个路由链自动添加它。

From there you have to either pass a format=json parameter which each AJAX request or setup a routing chain that automatically appends it.

有关一个略更安全的设置,你可以使用ajaxContext作为你的助手,只具有 XMLHtt prequest 头将送达JSON请求。

For a 'slightly' more secure setup you could use ajaxContext as your helper and only requests that have the XMLHttpRequest header will be served json.

这篇关于Zend框架:如何处理异常的Ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆