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
请求时,有没有办法填充$_POST
的php
。 请帮忙。
您需要将您的请求转换为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 );
玩得开心,