如何在 Angular.js $http.post 中指定 dataType: 'json'?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15205037/
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
How to specify dataType: 'json' in Angular.js $http.post?
提问by Paul
I would like to specify dataType: 'json'as in conventional jQuery $.ajax.
Is this possible with Angular.js $http.post?
我想dataType: 'json'在传统的 jQuery 中指定$.ajax。这可以用 Angular.js 实现$http.post吗?
采纳答案by Musa
From http://docs.angularjs.org/api/ng.$http
来自http://docs.angularjs.org/api/ng.$http
Transforming Requests and Responses Both requests and responses can be transformed using transform functions. By default, Angular applies these transformations:
Request transformations:
if the data property of the request config object contains an object, serialize it into JSON format. Response transformations:
if XSRF prefix is detected, strip it (see Security Considerations section below)
- if json response is detected, deserialize it using a JSON parser
转换请求和响应 请求和响应都可以使用转换函数进行转换。默认情况下,Angular 应用这些转换:
请求转换:
如果请求配置对象的 data 属性包含一个对象,则将其序列化为 JSON 格式。响应转换:
如果检测到 XSRF 前缀,则去掉它(请参阅下面的安全注意事项部分)
- 如果检测到 json 响应,则使用 JSON 解析器反序列化它
So no need to set a data type it is done automatically
所以不需要设置数据类型它会自动完成
回答by Jason Aden
You can use the HTTP Config object to set the headers:
您可以使用 HTTP Config 对象来设置标头:
$http({
method: 'POST',
url: 'somewhere.xyz',
headers: {
'Content-type': 'application/json'
}
})
回答by Mulaffer
I had the same problem, responseType:'json'solved the issue
我遇到了同样的问题, responseType:'json'解决了这个问题
You can use responseType:'json' instead of dataType:'json'
您可以使用 responseType:'json' 而不是 dataType:'json'
var promise = $http({
method: 'POST',
url: 'somewhere.xyz',
responseType:'json'
});
For further reference https://docs.angularjs.org/api/ng/service/$http#methods_jsonp
如需进一步参考 https://docs.angularjs.org/api/ng/service/$http#methods_jsonp

