当我通过 Angular $post 向 Codeigniter 发送数据时遇到问题。我正在使用这个 JS 代码:
$scope.user.first_name = 'first name';
$scope.user.last_name = 'last name';
$http({
method: 'POST',
url: '/registration',
data: {user: $.param($scope.user)},
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
}).then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response);
});
我的 PHP 基于 StackOverflow 的另一个答案,但仍然不起作用:
echo file_get_contents('php://input');
var_dump($this->input->post());
,但是如果我说:
var_dump($this->input->post('user'));
我看到响应 NULL,相同的是:
var_dump(json_encode($this->input->post()));
有或没有键“用户”。即使我使用:
var_dump($_POST);
对于响应,我得到空数组。
如何使用 Codeigniter 通过 $post Angular 服务发送和获取数据?
最佳答案
如果你想发送表单编码数据,你需要使用 $.param()
序列化整个数据对象
改变:
data: {user: $.param($scope.user)},
到
data: $.param(angular.copy({user: $scope.user})),
或者使用$httpParamSerializerJQLike
如果你使用默认的 $http
就可以了
$http.post( '/registration',$scope.user).then(...
在 php 中
$data = json_decode(file_get_contents('php://input'));
关于javascript - 使用 Angular $post 和 PHP Codeigniter 请求和响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38579763/