2015-12-14 114 views
5

我正在使用Google Api在Laravel 5.0中進行Google Oauth登錄。我得到了當前登錄用戶的電子郵件id_token的數據,現在我想將這些數據發送給控制器(SigninController)以調用我們自己的api,並通過Ajax將響應返回到前端(signin.blade.php)查詢。但是我的Ajax查詢不起作用。我在這裏附上代碼。ajax請求不爲laravel工作5.0

我Signin.blade.php文件的Ajax樣子(我已經包含CSRF頭):

$.ajax({ 
      url: '/signin/oauth', 
      type:"POST", 
      data: data, 
      headers: { 'X-CSRF-Token' : token}, 
      success:function(data){ 

       console.log(data); 
       if(data){ 
        console.log("Success nowwww for ajax expected data!"); 
        // window.location.href = '{{url("/home")}}'; 
       } 
       else{ 
        console.log("Success ajax ! But not expected data!"); 
        // window.location.href = '{{url("/signup")}}'; 
       } 

      },error:function(){ 
       alert("error!! ajax failure !!!!"); 
      } 
    }); 

我的routes.php文件是這樣的:

Route::post('/signin/oauth', [ 
     'uses' => '[email protected]', 
     'as' => 'post_signin_oauth', 
    ]); 

在我SigninController的signinProcessOauth功能正常「請求窗體「正在工作,但」請求 - > ajax()「可能無法正常工作。它看起來像:

 . 
    . 
    use Illuminate\Http\Request; 
    use Illuminate\Support\Facades\Session; 
    . 
    . 
    public function signinProcessOauth(Request $request) 
    { 
     $getData = $request->ajax(); 

     if ($getData) { 

     $authCode = $request['authCode']; 
     $idToken = $request['idToken']; 
     $userEmail = $request['userEmail']; 

       // call the api here and send the above data to the server and process the response like saving the cookie etc 

     return $authCode; // return according to the response,this will return in ajax success function,right now it is authcode just for testing purpose 
    } 

    return "error"; 
    } 

每次我運行代碼,我得到「錯誤!! ajax失敗!!!!」響應,即ajax的失敗函數被調用。我無法弄清楚問題在哪裏?或者有沒有其他方法可以將數據從視圖發送到控制器並獲取對前端的響應?

感謝您的耐心閱讀如此長的職務。 :) :)

+0

添加響應參數你'錯誤:function',讓我們知道特定的錯誤信息 - >'功能(jqXHR jqXHR,字符串textStatus,字符串errorThrown)' - 你可能需要額外的標題,如'內容-Type' – WhiteHat

+0

@WhiteHat,謝謝你的忠告。我嘗試使用contentType:'application/octet-stream; charset = utf-8'命令。但徒勞無益。我試圖在錯誤函數中傳遞一個參數並嘗試在控制檯中打印它。結果是:失敗ajax !! [object Object]。我檢查了我的瀏覽器中的網絡,它說:500,內部服務器錯誤。 :(標題,內容都差不多,不過AJAX請求正在使用「不緩存」。它可以是一個問題嗎? –

+0

首先檢查由郵遞員或其他工具的Ajax請求。 – dipesh

回答

0

在你的方法$request不是數組,其的對象。所以你需要使用->來訪問屬性。

0

更改您的網址如下:

url: '{!! route('post_signin_oauth') !!}' 

希望這會工作。