我正在使用带有 FOSUserBundle 的 Symfony2,并且我想使用 Ajax 进行用户登录。我使用扩展 DefaultAuthenticationFailureHandler 类的服务:
<?php
namespace Marquis\WebsiteBundle\Handler;
use Psr\Log\LoggerInterface;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
use Symfony\Component\Security\Http\HttpUtils;
class AuthenticationFailureHandler extends DefaultAuthenticationFailureHandler {
protected $translator;
public function __construct(HttpKernelInterface $httpKernel, HttpUtils $httpUtils, array $options, LoggerInterface $logger = null, Translator $translator = null) {
parent::__construct($httpKernel, $httpUtils, $options, $logger);
$this->translator = $translator;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
if($request->isXmlHttpRequest()) {
/* @var $formResponse RedirectResponse */
$formResponse = parent::onAuthenticationFailure($request, $exception);
$response = new JsonResponse(array('success' => false,
'message' => $this->translator->trans($exception->getMessage(), array(), 'FOSUserBundle'),
'form' => $formResponse->getTargetUrl()));
} else {
$response = parent::onAuthenticationFailure($request, $exception);
}
return $response;
}
}
它工作得很好,但我想将渲染视图转换为“表单”JsonResponse 值。
是否可以从 RedirectResponse 对象生成视图?