加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

CakePHP中的Ajax错误处理

发布时间:2020-12-13 13:26:13 所属栏目:PHP教程 来源:网络整理
导读:我想做一些非常类似于 this的事情,但是在CakePHP世界中寻找AJAX请求.目前我这样做: $this-autoRender = false;$this-response-statusCode(500); 它基于this.但是这个解决方案不允许我包含像Rails示例中的自定义消息,这样,在我的客户端错误处理程序中,我可以
我想做一些非常类似于 this的事情,但是在CakePHP世界中寻找AJAX请求.目前我这样做:
$this->autoRender = false;
$this->response->statusCode(500);

它基于this.但是这个解决方案不允许我包含像Rails示例中的自定义消息,这样,在我的客户端错误处理程序中,我可以显示500错误响应中包含的消息.

我如何在CakePHP中实现与Ruby on Rails示例相同的功能?

你可以按照Cookbook: http://book.cakephp.org/2.0/en/development/exceptions.html中的说明使用CakeExceptions但是如果你想使用自定义消息,我发现除了在生产模式下使用debug = 1之外别无他法:(

这是我使用内置方法的方法:

在你的控制器中:

if($this->request->is('ajax')){
    Configure::write('debug',1);
}

if(!$allowed) {
    throw new InternalErrorException('Keep your fingers away from me!'); // 500 error
}

在/app/View/Errors/error500.ctp中的AJAX调用中使用时,更改错误模板以输出除错误之外的任何内容:

<?php
if($this->request->is('ajax')):
    // Output for AJAX calls
    echo $name;

else:
    //Standard CakePHP output ?>
    <h2><?php echo $name; ?></h2>
    <p class="error">
        <strong><?php echo __d('cake','Error'); ?>: </strong>
        <?php echo __d('cake','An Internal Error Has Occurred.'); ?>
    </p>
    <?php
    if (Configure::read('debug') > 0 ):
        echo $this->element('exception_stack_trace');
    endif;

endif; ?>

然后,您可以解析AJAX中返回的文本.这是我使用的jQuery部分:

//...
error: function (request) {
    yourErrorShowingFunction(_this,request.responseText);
}
//...

希望这可以帮助 :)

如果有人知道如何在生产模式下使用自定义错误(不覆盖调试模式),我会非常高兴!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读