AngularJS - $http.post 将数据作为 json 发送
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24545072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS - $http.post send data as json
提问by Jhonatan Sandoval
I'm working on autocomplete directive with angularjs but having some issues.
我正在使用 angularjs 处理自动完成指令,但遇到了一些问题。
I have a form which have an autocomplete input. When i type something there, the term variableis sent as JSON:
我有一个具有自动完成输入的表单。当我在那里输入内容时,术语变量作为 JSON 发送:


But, when i use the same function (from different angular controller, but the same function) in another form the term variablesent perfectly and the autocomplete works fine:
但是,当我以另一种形式使用相同的功能(来自不同的角度控制器,但相同的功能)时,术语变量完美发送并且自动完成工作正常:


Here is my angular function:
这是我的角函数:
$scope.getCustomers = function (searchString) {
return $http.post("/customer/data/autocomplete",
{term: searchString})
.then(function (response) {
return response;
});
};
What do you think is wrong?
你觉得哪里不对?
回答by Swapnil Dalvi
Use JSON.stringify() to wrap your json
使用 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.
});
回答by Adrian B.
Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):
考虑在 $http.post 中显式设置标头(我放置了 application/json,因为我不确定您示例中的两个版本中的哪一个是有效的,但是您可以使用 application/x-www-form-urlencoded 如果这是另一个):
$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
return response;
});
回答by oneLeggedChicken
i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializerwill have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))
我认为最正确的方法是在执行“获取”请求时使用相同的代码 angular use 使用您$httpParamSerializer必须将其注入您的控制器,这样您就可以简单地执行以下操作而根本不必使用 Jquery, $http.post(url,$httpParamSerializer({param:val}))
app.controller('ctrl',function($scope,$http,$httpParamSerializer){
$http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

