2017-01-20 74 views
1

我嘗試使用Laravel 5.2 Auth使用Ajax創建登錄表單。使用Laravel使用Ajax登錄表單5.2

$(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默認登錄功能:

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); 
} 

/登錄返回索引頁作爲響應。 我需要關於錯誤消息或成功消息的json響應。據說,改變Laravel的核心功能並不可取。那我怎麼能得到它?

+3

發佈你的PHP代碼以及 –

+0

HTTP ://堆棧溢出.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request –

+0

add dataType:'json'in ajax if you want to get json response and post your php code –

回答

0

你可以嘗試jQuery中添加

dataType: 'JSON' 

或嘗試在會話存儲和使用

Redirect::back() 

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

我瞭解你的代碼示例只是複製AuthenticatesUser特徵。

因此,爲了避免大的變化,並使其發揮作用,只是這種替換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部分可以保持相同的:

$.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); 
     } 
    } 
}); 

但我個人更喜歡處理的不是提交的按鈕,而是通常的形式,以防止發生這種情況時,用戶公關只需點擊登錄按鈕即可。

檢查這個例子:

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部分:

$(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); 
      } 
     } 
    }); 
    }); 

}); 
+0

它有500(內部服務器錯誤),但我不知道它在哪裏。我把它發送到URL:「/ loginajax」(不/ /登錄),並在路由發送它LoginController @登錄功能,因爲了解它究竟做了什麼,但我不知道錯誤是 –

+0

發送到'/登錄'不'/ loginajax'錯誤500應該是類似於未找到路由的內容。 – num8er

+0

@NigarJafar我已經更新了我的答案,請檢查。如果你仍然不工作,所以加我skype:'anarjafarov',讓我們調試 – num8er

1

請試試這個

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); 
    } 
} 
+0

使用響應對象來設置狀態它比定義數字更安全:'Response :: HTTP_FORBIDDEN';) – num8er

+0

我應該添加一些控制器或\ vendor \ laravel \ framework \ src \ Illuminate \ Foundation \ Auth \ AuthenticatesUsers.php?有什麼區別嗎? –

+0

@NigarJafar其實你可以自由選擇,如果你知道Laravel是如何工作的。在你的情況下,我看到你已經擁有自己的代碼複製粘貼或從你嘗試使用的某個地方(或者由你之前的某個人編寫)。如果您只想發送表單字段並獲得json-ic響應並重新加載頁面,只需通過您的控制器的「登錄」操作響應json響應和狀態,其中2xx系列由「success」處理,4xx-5xx由' error'。 – num8er