问题
I am posting some data to a php page from angularjs controller using the $http method as shown below.
$scope.login = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password
};
$http.post('login.php', data).success(function(response){
console.log(response);
});
};
I know I can retrieve this data in php using :
$postdata = json_decode(file_get_contents('php://input'), true);
But I was wondering if there is better way in angularjs so I could use the simple $_POST in php to retrieve the data.
In jQuery we could just simply use $.post and those are available for php in $_POST. Why for angularjs that is not that simple.
Is there any way to populate $_POST of php when we do a $http post request in angularjs. Please help.
回答1:
You need to convert your request to php known format.
I use jQuery $.param method to build it. You can write your own.
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 is followed simple format:
username=Name&password=My%20Password
JSFiddle
回答2:
Got it working using jQuery $.param method. Thanks to vp_arth's answer. I just added this answer as it might help someone. This can be used if it is needed for only one request.
$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);
});
};
回答3:
well I just use this in my controller class, so all my post requests: normal ones with jQuery or the ones through angular all end up being in $_post
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty( $_POST ))
$_POST=$_REQUEST = json_decode( file_get_contents( 'php://input' ), true );
have fun,
来源:https://stackoverflow.com/questions/33540195/angularjs-http-post-to-php