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