mark一下:
初次使用angularjs在使用$http传递参数的时候,发现后台无论如何都获取不到参数,百度了一下,发现因为angularjs发送post请求时参数列表类型是 Payload,而后台想要接收参数的话,参数列表的类型需为 Formdata形成的kv模式的参数,所以需要对$http进行配置,发现两种配置模式,mark一下:
A:修改配置文件:
app.config(@H_404_9@function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
@H_404_9@var param = @H_404_9@function (obj) {
@H_404_9@var query = '',name,value,fullSubName,subName,subValue,innerObj,i;
@H_404_9@for (name @H_404_9@in obj) {
value = obj[name];
@H_404_9@if (value @H_404_9@instanceof Array) {
@H_404_9@for (i = 0; i < value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
@H_404_9@else @H_404_9@if (value @H_404_9@instanceof Object) {
@H_404_9@for (subName @H_404_9@in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
@H_404_9@else @H_404_9@if (value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
@H_404_9@return query.length ? query.substr(0,query.length - 1) : query;
};
// Override $http service's default transformRequest
$httpProvider.defaults.transformRequest = [@H_404_9@function (data) {
@H_404_9@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'}
})