【问题标题】:Symfony2 AuthenticationFailureHandler - JSON renderView from RedirectResponseSymfony2 AuthenticationFailureHandler - 来自 RedirectResponse 的 JSON renderView
【发布时间】:2013-09-18 17:42:55
【问题描述】:

我正在使用带有 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 对象生成视图?

【问题讨论】:

    标签: php ajax json symfony response


    【解决方案1】:

    如果我理解正确,您想渲染一个视图并在登录或注册页面上显示该视图吗?

    如果是这样,您可以直接返回您的视图,并从 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');
      }
    });
    

    【讨论】:

    • 谢谢,这可能是一个解决方案,但我想使用默认的 Symfony2 响应。我找不到获取 Reponse 对象而不是 RedirectResponse 的方法,但我用 jQuery 的 $.get 解决了这个问题(使用 RedirectResponse 对象中的 getTargetUrl() 函数)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 2014-07-13
    • 2017-10-19
    • 1970-01-01
    • 2019-07-05
    相关资源
    最近更新 更多