如何解决angularjs中post参数获取不到的问题

2025-03-09 23:52:34
推荐回答(2个)
回答1:

解决angularjs中post参数获取不到的问题的方法:
当使用angularjs发送post请求时:
1 $http({
2 method : "post",
3 url : "./account/add",
4 data : {name:"123",passwd:123}
5 })

后台springMVC接受不到参数
public String add(@RequestParam String name, @RequestParam String passwd) {

}

因为angularjs发送post请求时参数列表类型是 Payload(可以通过chrome调试工具的network查看), 而后台想要接收参数的话, 参数列表的类型需为 Form data(用jquery发送post请求时就是该类型), 所以需要做如下调整
$http({
method : "post",
url : "./account/add",
data : $.param(params),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})

回答2:

解决angularjs post方式提交时,获取不到参数
angular.module('MyModule', [], function ($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
var param = function (obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

for (name in obj) {
value = obj[name];

if (value instanceof Array) {
for (i = 0; i < value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if (value instanceof Object) {
for (subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if (value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}

return query.length ? query.substr(0, query.length - 1) : query;
};

// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function (data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
} ];
});

将这段代码添加到指定的模块上,作用是将 Content-Type 请求方式由application/json 变为 'application/x-www-form-urlencoded;charset=utf-8 。
$scope.save = function () {
$http.post(location.href + "?action=Save", {
aaa: "1111",
bbb: "2222"
}).success(function (r) {
alert(r);
}).error(function () {

});
}

这样后台就能正常的获取参数了