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 } } }解决 无用评论 打赏 举报