dtdh11647 2017-01-20 11:17
浏览 70

使用Laravel 5.2使用Ajax登录表单

I try to create login form with Ajax using Laravel 5.2 Auth.

$(document).ready(function(){
$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

$('#login').on('click',function(e){
e.preventDefault(); 

var formData = {
    email: $('#email').val(),
    password: $('#password').val(),
}
    $.ajax({
        type: "POST",
        url: "/login",
        data: formData,
        success: function (data) {
           location.reload();
        },
        error: function (data) {

        }
    });

});

})enter code here

Laravel default login function:

public function login(Request $request)
{
$this->validateLogin($request);

// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();

if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
    $this->fireLockoutEvent($request);

    return $this->sendLockoutResponse($request);
}

$credentials = $this->getCredentials($request);

if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
    return $this->handleUserWasAuthenticated($request, $throttles);
}

// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
    $this->incrementLoginAttempts($request);
}

return $this->sendFailedLoginResponse($request);
}

/login return index page as a response. I need json response about error messages or success message. It is said that changing Laravel core functions is not advisable. Then how can I get it?

  • 写回答

4条回答 默认 最新

  • duanjing2013 2017-01-20 11:47
    关注

    You can try adding in jquery

    dataType: 'JSON'
    

    or Try to store in Session and use

    Redirect::back()
    

    or

    return redirect($this->loginPath())
           ->withInput($request->only('email', 'remember'))
           ->withErrors([
                 'email' => $this->getFailedLoginMessage(),
            ]);
    
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大