在 Laravel 4.2 中使用 Ajax,一旦用户通过身份验证,登录表单不会重定向到预期页面

Bob*_*Bob 5 ajax jquery laravel

我在 Laravel 4.2 中使用jQuery 验证插件,并希望通过 Ajax 提交登录表单。一切正常,但是当表单经过验证并且用户经过身份验证时,表单不会重定向到预期页面。

实际上,用户已经过身份验证(因为当我刷新时,页面会转到用户的个人资料),但Redirect::intended('/')提交表单时不起作用。

这是我的 jQuery 代码:

    var validator = $('#login-form').validate({
    rules: {
        email: {
            required: true
        },

        password: {
            required: true
        }
    },

    submitHandler: function(form) {

        $.ajax({
            url: 'login',
            type: 'post',
            cache: false,
            data: $(form).serialize(),
            dataType: 'json',
            success:function(data){
                $('.message').text(data.error);
                $('.message').fadeIn(200);
            }
        });
        $(form).ajaxSubmit();
    }
});
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

class AccountController extends BaseController {

    public function logInForm() {
        return View::make('pages.login');
    }

    public function logIn() {
        $validator = Validator::make(Input::all(),
            array(
                'email'     => 'required|email',
                'password'     => 'required'
            )
        );

        if ($validator->fails()) {
            return Response::json([
                'error' => $validator->errors()->first()
            ]);

        } else {
            $auth = Auth::attempt(array(
                'email'     => Input::get('email'),
                'password'     => Input::get('password')
            ));

            if ($auth) {
                return Redirect::intended('/');

            } else {
                return Response::json([
                    'error' => 'Email or password is wrong.'
                ]);

            }
        }

        return Response::json([
            'error' => 'Sorry, your request could not be proceeded.'
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*Joe 2

您最好在响应中返回预期位置,然后让客户端执行重定向。

if ($auth) {
    return Response::json(['redirectUrl' => 'http://domain.com/dash']);
}
Run Code Online (Sandbox Code Playgroud)

并且在客户端中

window.location = response.redirectUrl;
Run Code Online (Sandbox Code Playgroud)