AngularJS – $ http.post发送数据为json

我正在与angularjs的autocomplete指令,但有一些问题。

我有一个有自动完成input的表单。 当我键入一些东西, 术语variables作为JSON发送:

在这里输入图像说明

但是,当我使用相同的function(从不同的angular度控制器,但相同的function)在另一种forms的术语variables发送完美,自动完成工作正常:

在这里输入图像说明

这是我的angularfunction:

$scope.getCustomers = function (searchString) { return $http.post("/customer/data/autocomplete", {term: searchString}) .then(function (response) { return response; }); }; 

你认为什么是错的?

使用JSON.stringify()来包装你的json

 var parameter = JSON.stringify({type:"user", username:user_email, password:user_password}); $http.post(url, parameter). success(function(data, status, headers, config) { // this callback will be called asynchronously // when the response is available console.log(data); }). error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. }); 

我认为最正确的方法是使用相同的一段代码angular度使用时,使用您的“get”请求$httpParamSerializer将不得不将其注入到您的控制器,所以你可以简单地做下面的事情,而不必使用JQuery的, $http.post(url,$httpParamSerializer({param:val}))

 app.controller('ctrl',function($scope,$http,$httpParamSerializer){ $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal})); } 

考虑明确设置$ http.post中的标题(我把应用程序/ JSON,因为我不知道你的例子中的两个版本中的哪一个是工作的,但你可以使用application / x-www-form-urlencoded if这是另一个):

 $http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} }) .then(function (response) { return response; });