weixin_33735077 2015-11-03 20:26 采纳率: 0%
浏览 37

Session Expire Symfony 2 Ajax

My application uses ajax to request data. I'm using Symfony2, and when the session expires and I make a request with ajax, the login form is shown inside the main area on my application, and not as another view as should be. How can solve this problem. Thanks

  • 写回答

2条回答 默认 最新

  • weixin_33743703 2015-11-03 20:45
    关注

    I would suggest creating event listener which will be listening for every request:

    services.yml:

    your_request_listener:
        class: Acme\AppBundle\EventListener\RequestListener
        arguments: [@security.token_storage]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onRequest }
    

    In this event listener I would check for type of request so this would be only Ajax request listener. When request is ajax type then I would check if session has expired - if so, I would create response which will be valid response for ajax request (i.e. JsonResponse) and set this response to be sent to user.

    class RequestListener
    {
        private $tokenStorage;
    
        public function __construct(TokenStorageInterface $tokenStorage)
        {
            $this->tokenStorage = $tokenStorage;
        }
    
        public function onRequest(GetResponseEvent $event)
        {
            $request = $event->getRequest();
            if (!$request->isXmlHttpRequest()) {
                return; //we dismiss requests other than ajax
            }
    
            //now you check if user is authenticated/session expired/whatever you need
            $token = $this->tokenStorage->getToken();
            if ($token === null) {
                //now you create response which you would expect in your js doing ajax, for example JsonResponse
                $response = new JsonResponse(); //you should give some content here
                $event->setResponse($response); //now you override response which will be sent to user
            }
    
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度