您的位置:首页 > 编程语言 > Java开发

angular的post请求,springmvc后台接收不到参数的解决方案

2017-08-04 10:43 1416 查看
angular的post请求,后台接收参数为null的解决方案。

1、确定angularjs,如何使用,才是post请求。angularjs实际开发过程,发现,想使用post请求,不仅仅需要设置,method:'POST',还需要

传参的时候使用data (注:如果使用params传参,angularjs默认使用 get请求),如下:

$http({
method:'POST',
url:baseUrl+url,
data : data
}).then(function(result) {
alert(result.data);
});2、angularjs的post请求的"Content-Type"默认为" application/josn",而 jquery的post请求的"Content-Type"默认为" application/x-www-form-urlencoded"
故,要想springmvc后台接收到参数。需要修改angularjs的post请求的Content-Type为x-www-form-urlencodedand。当然,此时后台仍然接受不到数据。

3、默认情况下,jQuery传输数据使用Content-Type: x-www-form-urlencodedand和类似于"foo=bar&baz=moe"的序列,

然而AngularJS,传输数据使用Content-Type: application/json和{ "foo": "bar", "baz": "moe" }这样的json序列。所以把Content-Type设置成x-www-form-urlencodedand

之后,还需要转换序列的格式。

.config(function($httpProvider) {
$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [function(data) {
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
var param = function(obj) {
var query = '';
var 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;
};

return angular.isObject(data) && String(data) !== '[object File]'
? param(data)
: data;
}];
})
完成以上修改,springmvc后台已经可以正常接收到参数了,大功告成!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: