angularJS $http 传参踩坑

默认情况下,jQuery传输数据使用Content-Type: x-www-form-urlencodedand和类似于"foo=bar&baz=moe"的序列,然而AngularJS,传输数据使用Content-Type: application/json和{ "foo": "bar", "baz": "moe" }这样的json序列。

所以要改为:headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

$http({
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },//跨站必须,否则浏览器自动将method改为options
//headers: { 'Content-Type': 'application/json' },
url: "api",
//data: $scope.params
data: $.param($scope.params) //jquery方法,把对象改为a=1&b=2格式,否则后台接收不到,因为angularJS序列号对象的方式和jquery不一样
}).success(function(data) {
alert(JSON.stringify(data));
layer.closeAll('loading');
});


如果要用headers: { 'Content-Type': 'application/json' }方式,参数类型为Payload,后台需使用@RequestBody接收参数

 

posted @ 2020-03-11 17:35  覃上  阅读(336)  评论(0编辑  收藏  举报