如何使用AJAX

时间:2014-01-08 19:23:20

标签: ajax symfony fosuserbundle

我是AJAX的新手。但我正在努力学习这是如何工作的。 我正在使用带有fos用户包的symfony2,我想在我的登录表单中实现AJAX。 所以我这样做:

login.html.twig

<script>
$('#_submit').click(function(e){
    e.preventDefault();
    $.ajax({
        type        : $('form').attr( 'method' ),
        url         : $('form').attr( 'action' ),
        data        : $('form').serialize(),
        success     : function(data, status, object) {
            if (data.sucess == false) {
                $('.tab-1').prepend('<div />').html(data.message);
            } else {
                window.location.href = data.targetUrl;
            }
        }
});
</script>
<div id="tab-1" class="login_form">
<form action="{{ path("fos_user_security_check") }}" role="form" method="post">
<label for="username"><strong>User Name / Email Address</strong>
    <input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
</label>
<label for="password"><strong>Password</strong>
    <input type="password" id="password" name="_password" required="required" />
</label>
<label for="password"><strong>Remember Me</strong>
    <input type="checkbox" id="remember_me" name="_remember_me" value="on" />
</label>
<input type="submit"  class="submitBut" id="_submit" name="_submit" value="{{  'security.login.submit'|trans({}, 'FOSUserBundle') }}" />
</form>
</div>

提交时请转到此文件: -

<?php

namespace XXXX\UserBundle\Handler;

use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use     Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;

class AuthenticationHandler implements AuthenticationSuccessHandlerInterface,        AuthenticationFailureHandlerInterface
{

protected $router;
protected $security;
protected $userManager;
protected $service_container;

public function __construct(RouterInterface $router, SecurityContext $security, $userManager, $service_container)
{
    $this->router = $router;
    $this->security = $security;
    $this->userManager = $userManager;
    $this->service_container = $service_container;

}
public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
    if ($request->isXmlHttpRequest()) {
        $result = array('success' => true);
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    else {
        // Create a flash message with the authentication error message
        $request->getSession()->getFlashBag()->set('error', $exception->getMessage());
        $url = $this->router->generate('fos_user_security_login');

        return new RedirectResponse($url);
    }

    return new RedirectResponse($this->router->generate('anag_new')); 
} 
public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
    $translator = new Translator('fr_FR');
    //$result = array(
    //  'success' => false, 
    //  'function' => 'onAuthenticationFailure', 
    //  'error' => true, 
    //  'message' => $this->translator->trans($exception->getMessage(), array(), 'FOSUserBundle')
    //);
    $result = array('success' => false);
    $response = new Response(json_encode($result));
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}
}

提交表单后,请在login_check url中显示我:

{"success":false}

但是我想在结果为false时返回我试图登录的同一个表单(我的意思是同一个弹出式div)?

我的代码ajax或操作返回有什么问题? 或者我回来了吗?

1 个答案:

答案 0 :(得分:1)

window.location将重新加载整个页面。我认为这不是我想要的结果,因为你使用的是AJAX(AJAX的重点是不重新加载页面),如果登录不成功,你可能会显示错误信息。 我建议你在html表单中添加一个错误div

  

<div class='error' style="display:none" > ooups an erro occured </div>

然后在ajax调用中显示它或添加重要的消息错误:

       if (data.sucess == false) {
                $('.tab-1').prepend('<div />').html(data.message);
            } else {
                $('.error').show();
            }