【问题标题】:Rendering ajax layout from cake's beforeFilter using requestAction使用 requestAction 从蛋糕的 beforeFilter 渲染 ajax 布局
【发布时间】:2015-02-05 14:15:28
【问题描述】:

我有一个场景在 AppController 的 beforeFilter 中,我有一个会话检查方法来检查是否设置了一些会话数据。如果没有,用户将被重定向到登录页面。

这适用于服务器端操作调用,但是当进行 ajax 调用时,beforeFilter 似乎忽略了 requestAction.. 这是我的代码

AppController beforeFilter

public function beforeFilter(){
  if($this->RequestHandler->isAjax()) {
     echo $this->requestAction("/users/ajax_login", array('return'));
  }else{
     $this->redirect('/login');
  }
}

ajax_login action

function ajax_login() {
    $this->render('ajax_login', 'ajax');
}

ajax_login view

<script type="text/javascript">
window.location = '<?php echo 'http://'.$_SERVER['HTTP_HOST'].$html->url('/login').'"'; ?>';
</script>;

基本上这应该呈现一个 ajax 布局。但是,视图没有被呈现,因此重定向不起作用。

当然我得到一个错误,因为通过 ajax 调用的操作仍在被调用,由于会话到期而引发错误 net::ERR_CONNECTION_RESET

【问题讨论】:

    标签: php ajax cakephp


    【解决方案1】:

    我找到了一个可行的替代解决方案。这是代码:

    class AppController extends Controller {
        var $components = array('Auth', 'RequestHandler');
    
        function beforeFilter() {
            if($this->RequestHandler->isAjax()) {
                if(!$this->Session->check('data')) {
                    header('Requires-Auth: 1'); // set header and make sure to exit
                    exit;
                }
            }
        }
    } 
    

    然后只需要一个 jquery (acaxComplete) 事件侦听器来检查标题,如果它设置为 1,则重定向到登录页面。

    <script>
       $(document).ready(function() {
        $(document).ajaxComplete(function(event, request, settings){
            var requiresAuth;
            try { requiresAuth = request.getResponseHeader('Requires-Auth') }
            catch(e) {}
    
            if (requiresAuth == 1) {
                window.location = "<?php echo $this->Html->url(array('controller' => 'users', 'action' => 'login')); ?>";
                return false;
            }
        });
       });
    </script>
    

    这很好用。但是,我仍然对为什么我的第一个解决方案不起作用感兴趣。欢迎任何意见.. 干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多