mark一下:
初次使用angularjs在使用$http传递参数的时候,发现后台无论如何都获取不到参数,百度了一下,发现因为angularjs发送post请求时参数列表类型是 Payload,而后台想要接收参数的话,参数列表的类型需为 Formdata形成的kv模式的参数,所以需要对$http进行配置,发现两种配置模式,mark一下:
A:修改配置文件:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
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;
}];
});
此时调用的时候data里就可以写KV模式的参数了:
$http({
method : 'POST',url : '/',data : {'username': $scope.username,"password": $scope.password},})
B:传递参数修改:
这种感觉比较简答,mark下:
$http({
method : 'POST',url : '/',data : $.param({'username': $scope.username,"password": $scope.password}),headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})