【发布时间】:2017-09-22 12:57:37
【问题描述】:
我正在尝试访问此 REST API,它接受三个参数:
stationId, crusherId, monthYear
我在 AngularJS 中这样做是:
$http({
//headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
//headers: {'Content-Type': 'application/json; charset=UTF-8'},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json'
},
url: 'https://myurl../api/getHPData',
method: 'POST',
data: {
stationId: 263,
crusherId: 27,
monthYear: '2016-4'
}
})
.then(function(data, status, headers, config) {
//console.log(JSON.stringify(response));
console.log(data);
})
.catch(function(error){
//console.log("Error: " + JSON.stringify(error));
console.log(error);
})
但我总是得到这个:
对象{数据:"{"result":"false"}",状态:200,配置:对象,状态文本:"OK",标题:函数}
或
{"data":"{\"result\":\"false\"}","status":200,"config":{"method":"POST","transformRequest":[null] ,"transformResponse":[null],"headers":{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8","Accept":"application/json"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":" 2016-4"}},"statusText":"OK"}
如果我将header Content-Type 更改为:
headers: {'Content-Type': 'application/json; charset=UTF-8'},
它给出:
Object {data: null, status: -1, config: Object, statusText: "",headers: function}
或
{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers": {“内容类型”:“应用程序/json; charset=UTF-8","Accept":"应用程序/json,文本/纯文本, /"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}}, "statusText":""}
我做错了什么,请帮助我。
Plunker 来了:
https://plnkr.co/edit/57SiCdBZB2OkhdR03VOs?p=preview
(编辑)
注意:
我可以在jQuery 中这样做:
<script>
$(document).ready(function() {
get_homepage_data(263, 27, '2016-04');
function get_homepage_data(stationIds, crusherIds, date) {
var url = "https://myurl../api/getHPData";
var data_to_send = {
'stationId': stationIds,
'crusherId': crusherIds,
'monthYear': date
};
console.log("Value is: " + JSON.stringify(data_to_send));
//change sender name with account holder name
// console.log(data_to_send)
$.ajax({
url: url,
method: 'post',
dataType: 'json',
//contentType: 'application/json',
data: data_to_send,
processData: true,
// crossDomain: true,
beforeSend: function () {
}
, complete: function () {}
, success: function (result1) {
var Result = JSON.parse(result1);
var value_data = Result["valueResult"];
var foo = value_data["gyydt"];
console.log("Log of foo is: " + foo);
var foo2 = 0;
// 10 lac is one million.
foo2 = foo / 1000000 + ' million';
console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2);
}
, error: function (request, error) {
return false;
}
});
}
}); // eof Document. Ready
</script>
上面脚本的输出是script是:
- 值为:{"stationId":263,"crusherId":27,"monthYear":"2016-04"}
- XHR 完成加载:POST “https://myurl../api/getHPData”。
- foo 的日志是:26862094
- “26862094”百万为:2686.2094万
这是完美的。 :)
【问题讨论】:
标签: angularjs rest post angular-http