我正在使用Symfony2和FOSUserBundle,我想使用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;
}
}
它工作得很好,但我希望将渲染视图转换为'form'JsonResponse值。
是否可以从RedirectResponse对象生成视图?
答案 0 :(得分:0)
如果我理解正确,你想渲染一个视图并在登录或注册页面上显示该视图吗?
如果是这样,您可以直接返回您的视图,并从javascript代码解析为html并附加到您想要的任何位置。
return $this->twig->render("SampleBundle:sample.html.twig", $data); //$data is not required
你可以像这样将加载的html附加到容器中;
$.ajax({
dataType:"html",
success: function(response){
response.append('#container');
}
});