带有ajax的表单submition后带有json结果的空白页

时间:2017-03-07 16:27:55

标签: php jquery ajax laravel

我正在尝试使用ajax登录我的Web应用程序,但是当我提交登录表单时,我得到一个带有json响应的空白页面,例如成功登录时我得到:

{"success":true}

我得到错误的凭据:

{"fail":true,"errors":"Email or password is incorrect"}

我收到错误的电子邮件或密码(验证错误):

{"fail":true,"errors":{"email":["The email field is required."],"password":["The password field is required."]}}

我的js文件包含这段代码:

$('#loginForm').submit('click',function(e){
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    })

e.preventDefault();

var formData = $(this).serialize();

$.ajax({
    type: "POST",
    url: $(this).attr("action"),
    dataType: 'json',
    data: formData,
    success: function (data) {
        window.location.replace("localhost:8000");
    },
    error: function (data) {
        $.each(data.errors, function(index,value) {
            var errorDiv = '#'+index+'_error';
            $(errorDiv).html(value);
        });
    }
});
});

在我的控制器中,我有登录功能:

public function login(Request $request){
        try{
            $validate = Validator::make($request->all(),[
                'email' => 'required|max:320',
                'password' => 'required|max:150',
                'remember_me' => 'nullable|accepted'
            ]);

        if($validate->fails()){
            return response()->json(array(
                'fail' => true,
                'errors' => $validate->getMessageBag()->toArray()
            ));
        }

        $rememberMe = $request->remember_me ? true : false;

        if(Sentinel::authenticate(['username'=>$request->email, 'password' => $request->password], $rememberMe)){
            return response()->json(array(
                'success' => true
            ));
        }
        elseif(Sentinel::authenticate(['email'=>$request->email, 'password' => $request->password], $rememberMe)){
            return response()->json(array(
                'success' => true
            ));
        }
        else{
            return response()->json(array(
                'fail' => true,
                'errors' => 'Email or password is incorrect'
            ));
        }
    }
    catch(ThrottlingException $e) {
        $delay = $e->getDelay();

        return redirect('/')->with('error',"After too many login attempts\n you've banned for $delay seconds!");
    }
    catch(NotActivatedException $e) {
        return redirect('/')->with('error','Your account is not activated!');
    }
    catch(Exception $e){
        return redirect('/')->with('error',$e->getMessage());
    }
}

形式:

{{ FORM::open(['url' => 'loginua','id'=>'loginForm']) }}
<div class="input-container">
    {{ FORM::text('email', null, ['placeholder' => 'E-mail or Username','id'=>'email', 'autofocus' => 'autofocus','required' => 'required']) }}
    <i class="fa fa-envelope-o"></i>
    <div id="#email_error"></div>
</div>
<div class="input-container">
    {{ FORM::password('password', ['placeholder' => 'Password','id' => 'password', 'required' => 'required']) }}
    <i class="fa fa-unlock"></i>
    <div id="#email_error"></div>
</div>
<div class="input-container">
    <label>
        <span class="radio">
            {{ FORM::checkbox('remember_me')}}
            <span class="radio-value" aria-hidden="true"></span>
        </span>
        <span>Remember me</span>
    </label>
</div>
<div class="input-container">
    {{ FORM::submit('Sign in',['class' => 'btn-style', 'name' => 'sign_in','id'=>'sign_in']) }}
</div>
<div class="user-box-footer">
    <p>Dont have account?<br><a href="{{url('register')}}">Sign up as User</a></p>
    <p><a href="{{url('recovery')}}">Lost password?</a></p>
    <p id="0_error"></p>
</div>
{{ FORM::close() }}

路线:

Route::post('loginua', 'PagesController@login');

我不知道为什么没有触发成功或失败的jquery。提前谢谢!

2 个答案:

答案 0 :(得分:0)

使用

$('#loginForm').on('submit',function(e){

而不是

$('#loginForm').submit('click',function(e){

答案 1 :(得分:0)

问题在于视图文件中的元标记,我不得不添加这行代码以对应于ajaxSetup:

<meta name="csrf-token" content="{{csrf_token()}}"/>

感谢大家的提示。