2016-06-10 34 views
0

我試圖通過Angularjs向Symfony發送帶有用戶名和密碼的ajax請求,但我無法訪問post變量。這裏是我的代碼:symfony通過Angularjs發佈數據

HTML:

<div> 
         <input type="text" 
         class="form-control defaultPassword" 
         ng-model="username" 
         placeholder="username"> 
        </div> 
        <div class="form-group"> 
         <input type="password" 
         ng-model="password" 
         class="form-control {% verbatim %}{{ passwordBox }}{% endverbatim %}" 
         placeholder="password"> 
        </div> 
        <div> 
         <span>{% verbatim %}{{ message }}{% endverbatim %}</span> 
         <button id="submitBtn" class="btn" ng-click="login()">login</button> 
        </div> 

AngularController

todoApp.controller("LoginController", 
function LoginController($scope, $http){ 

    $scope.username = ""; 
    $scope.password = ""; 

    $scope.login = Login; 

    function Login(){ 
     $http({ 
      method: 'POST', 
      url: '/api/login', 
      data: { 
       username: $scope.username, 
       password: $scope.password 
      }, 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
     }).then(function successCallback(response) { 
      console.log(response); 
      }, function errorCallback(response) { 
      alert("error"); 
      });; 
    } 

});

這裏是symfony的控制器:

/** 
* @Route("/api/login") 
* @Method("POST") 
*/ 
public function apiLogin(Request $request){ 
    $us = $request->request->get("username");   
} 

檢索數據不工作的這種方法。我可以看到用戶名和密碼正在發送,但我無法訪問它們。你能幫我找到另一種讓他們進入symfony控制器的方法嗎?

+1

的[?我如何使用與$ HTTP在AngularJS urlencoded的表格數據(可能的複製http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded - 形式 - 數據 - 與-HTTP-在-angularjs)。 [第二個答案](http://stackoverflow.com/a/30970229/283366)是更好的選擇 – Phil

回答

0

$http({ 
    method : 'POST', 
    url  : url, 
    headers : {'Content-Type': 'application/x-www-form-urlencoded'}, 
    data : JSON.stringify(dataObj) 
}) 
.success(function() 
{ 
    console.error("Done"); 
}) 
.error(function(dataObj) 
{ 
    console.error("Error"); 
}); 

的Symfony

包括:

use Symfony\Component\HttpFoundation\Request; 
use FOS\RestBundle\Controller\Annotations\Get; 
use FOS\RestBundle\Controller\Annotations\Post; 

功能:

/** 
    * POST Route annotation. 
    * @Post("/api/login") 
    */ 
    public function apiLoginAction(Request $request) 
    { 
     $parameters = $request->request->all();