向后台发起异步请求的方法有常用的有get和post两种,请求的内容也是不同的,实际工作中估计也都遇到过发送给后台的数据后台接受不到的情况,现今整理一下。
首先,配置文件
$httpProvider.defaults.transformRequest = [function(data) {
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];
if(subValue != null){
fullSubName = name + '.' + subName;
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
}
else if(value !== undefined ) {
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;
}];
$httpProvider.defaults.useXDomain = true;
}]);
FORM表单向后台传数据
$http({
method:'POST',
url:'data.json',
dataType:'json',
data:JSON.stringify(data)
}).success(function(data){console.log(data)});
String向后台传数据
$http({
method:'post',
url:'data.json',
headers : { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data:{orderstatus:$scope.x}
}).success(function(data){console.log(data);})
向后台传数组的
$http({
method:'POST',
url:'data.json',
headers : {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'},
data:{ids:data.join(',')},
}).success(function(data){console.log(data.status);}