无法使用AngularJS post方法获取正确的数据

这是我第一次和AngulerJS合作。 我正在尝试将数据发布到服务器。

AngularJS代码

  var app = angular.module("myApp", []); var BASE_URL = "http://localhost/project/api/Data/"; var GET_DATA = BASE_URL+"get_data"; console.log(GET_DATA); app.controller('myCtrl', function($scope, $http) { var inputs = { "user_id": "3"}; var config = { headers : { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' } } $http.post(GET_DATA , inputs, config) .success(function (response, status, headers, config) { $scope.content = response.error; $scope.statuscode = response.status; $scope.statustext = response.statusInfo; console.log(response); }) .error(function (data, status, header, config) { $scope.ResponseDetails = "Data: " + data + "
status: " + status + "
headers: " + header + "
config: " + config; }); });

此代码将数据发布到服务器,但使用有线格式。 下面是我的print_r($_POST); 结果:

 Array ( [{"user_id":"3"}] => [0] => ) 

这是错误的结果,我期待着类似的东西

 Array ( user_id => 3 ) 

注意:我在服务器端使用CodeIgniter框架。

您可以在json发送您的post数据:

 $http.post(GET_DATA , {"user_id": "3"}) .success(function (response, status, headers, config) { $scope.content = response.error; $scope.statuscode = response.status; $scope.statustext = response.statusInfo; console.log(response); }) .error(function (data, status, header, config) { $scope.ResponseDetails = "Data: " + data + "
status: " + status + "
headers: " + header + "
config: " + config; }); });

在服务器端,您可以获得如下的发布数据:

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

当请求内容类型为application / x-www-form-urlencoded`时,您必须以urlencoded格式对post正文中的数据进行编码。 这应该是这样的:

 var inputs = 'student_id=3'; 

虽然写下旧问题的答案不是正确的做法,但我想发布这个答案,以便其他人可以随时提供帮助。

首先,要了解发生这种事情的原因。 原因是,AngularJS不会自动序列化传递给POST请求的数据(参数)。 因此,我们必须使用$httpParamSerializerJQLike序列化数据,该数据可用作AngularJS服务。 此外,发布数据的默认内容类型是application / json。 因此,我们需要将post请求的Content-type标头覆盖到application / x-www-form-urlencoded,以便通过$ _POST访问发布的值。

现在角度也提供了$httpParamSerializer服务但差异$httpParamSerializerJQLike是一个对象也包含另一个对象所以如果使用前者,那么内部对象将不会被序列化,即所有嵌套对象都不会用$httpParamSerializer序列化但是它不是$httpParamSerializerJQLike的情况。

你可以在这里查看差异: AngularJS $ httpParamSerializer服务DOC

现在,我们可以通过在角度JS中使用$httpParamSerializerJQLike服务,而不是jsonphp对数据进行编码和解码,我们可以在Angular JS中实现这一点:

 $http({ url: myUrl, //post your url here method: 'POST', data: $httpParamSerializerJQLike({ 'user_id': '3'}), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); 

在codeigniter中,您可以通过普通语法获取发布的数据,即$this->input->post('user_id');

有关更多信息……您可以参考上面提到的链接…

希望它可以帮助你……