使用 Laravel 5.2 的 Ajax 登录表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41762405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Login Form with Ajax using Laravel 5.2
提问by Nigar Jafar
I try to create login form with Ajax using Laravel 5.2 Auth.
我尝试使用 Laravel 5.2 Auth 使用 Ajax 创建登录表单。
$(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:
Laravel 默认登录功能:
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?
/login 返回索引页作为响应。我需要有关错误消息或成功消息的 json 响应。据说改Laravel核心功能是不可取的。那我怎样才能得到呢?
回答by num8er
As I understood Your code example is just copy of AuthenticatesUsertrait.
据我了解,您的代码示例只是AuthenticatesUsertrait 的副本。
So to avoid big changes and make it work, just replace default controller code in app/Http/Controllers/LoginController.phpwith this:
因此,为了避免大的更改并使其工作,只需将默认控制器代码替换为app/Http/Controllers/LoginController.php:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
protected function username() {
return 'email';
}
public function login(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$authSuccess = Auth::attempt($credentials, $request->has('remember'));
if($authSuccess) {
$request->session()->regenerate();
return response(['success' => true], Response::HTTP_OK);
}
return
response([
'success' => false,
'message' => 'Auth failed (or some other message)'
], Response::HTTP_FORBIDDEN);
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/');
}
}
js part can keep the same:
js 部分可以保持不变:
$.ajax({
type: "POST",
url: "/login",
data: formData,
dataType:'json',
success: function (response) {
if(response.success) {
location.reload();
}
},
error: function (jqXHR) {
var response = $.parseJSON(jqXHR.responseText);
if(response.message) {
alert(response.message);
}
}
});
but I personally prefer to handle not the button that does submit, but the form generally, to prevent this happen when user press enterbutton than just click on the login button.
但我个人更喜欢处理不是提交的按钮,而是一般的表单,以防止在用户按下enter按钮而不是单击登录按钮时发生这种情况。
check this example:
检查这个例子:
html part:
html部分:
<form class="login" action="{{ url('/login') }}" method="post" data-type="json">
<input type="text" name="email">
<input type="password" name="password">
<button type="submit">login</button>
</form>
js part:
js部分:
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('form.login:first').on('submit', function(e){
e.preventDefault();
var $this = $(this);
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: $this.serializeArray(),
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
location.reload();
}
},
error: function (jqXHR) {
var response = $.parseJSON(jqXHR.responseText);
if(response.message) {
alert(response.message);
}
}
});
});
});
回答by ToJ
Please try this one
请试试这个
use Validator;
use Auth;
public function postUserLogin(Request $request) {
$credentials = array_trim($request->only('email', 'password'));
$rules = ['email' => 'required|email|max:255',
'password' => 'required'
];
$validation = Validator::make($credentials, $rules);
$errors = $validation->errors();
$errors = json_decode($errors);
if ($validation->passes()) {
if (Auth::attempt(['email' => trim($request->email),
'password' => $request->password,
], $request->has('remember'))) {
return response()->json(['redirect' => true, 'success' => true], 200);
} else {
$message = 'Invalid username or password';
return response()->json(['password' => $message], 422);
}
} else {
return response()->json($errors, 422);
}
}
回答by Harsh Pawar
You can try adding in jquery
您可以尝试在 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(),
]);
回答by Arshid KV
Add as follows
添加如下
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*
* @throws \Illuminate\Validation\ValidationException
*/
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return response()->json( $this->sendLockoutResponse($request));
}
if ($this->attemptLogin($request)) {
return response()->json( $this->sendLoginResponse($request) );
}
$this->incrementLoginAttempts($request);
return response()->json($this->sendFailedLoginResponse($request));
}

