AngularJS HTTP发布到PHP

我使用$http方法从angularjs控制器向php页面发布一些数据,如下所示。

 $scope.login = function(){ var data = { 'username' : $scope.username, 'password' : $scope.password }; $http.post('login.php', data).success(function(response){ console.log(response); }); }; 

我知道我可以使用以下方法在php检索此数据:

 $postdata = json_decode(file_get_contents('php://input'), true); 

但是我想知道在angularjs是否有更好的方法,所以我可以使用php的简单$_POST来检索数据。

jQuery我们可以简单地使用$.post ,这些可用于$_POST php 。 为什么angularjs并不那么简单。 当我们在angularjs执行$http post请求时,有没有办法填充$_POSTphp 。 请帮忙。

您需要将您的请求转换为php known格式。
我使用jQuery $.param方法来构建它。 你可以自己写。

 app.config(['$httpProvider', function($http) { $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; $http.defaults.transformRequest = function(data) { return $.param(data); }; }]); 

urlencoded遵循简单格式:

 username=Name&password=My%20Password 

的jsfiddle

使用jQuery $.param方法工作。 感谢vp_arth的回答。 我刚刚添加了这个答案,因为它可能有助于某人。 如果仅需要一个请求,则可以使用此选项。

 $scope.login = function(){ var data = { 'username' : $scope.username, 'password' : $scope.password }; $http({ url: "login.php", method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: $.param(data) }).success(function(response){ console.log(response); }); }; 

好吧,我只是在我的控制器类中使用它,所以我的所有post请求:正常的jQuery或通过角度的所有最终都在$_post

  if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty( $_POST )) $_POST=$_REQUEST = json_decode( file_get_contents( 'php://input' ), true ); 

玩得开心,