1.问题原因
默认情况下,jQuery传输数据使用Content-Type: x-www-form-urlencodedand和类似于"name=zhangsan&age=18"的序列,然而AngularJS,传输数据使用Content-Type: application/json和{ "name": "zhangsan", "age": "18" }这样的json序列。
2.解决办法
A.服务端进行修改,在Controller接收参数的方法中,对象前加 @RequestBody (注:要用对象的方式来接参数)
B.客户端修改
$http.post(url,{},{params:{"name": "zhangsan", "age": "18"}}).success(function(data){
});
$http.get(url,{params:{"name": "zhangsan", "age": "18"}}).success(function(data){
});
C.修改Angular的$httpProvider的默认处理:http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/ (适用于post,推荐)
var starter = angular.module('module',['ionic','ui.router']).run(function(){});
starter.config(['$httpProvider', 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;
};
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
}]);
书上说到可以通过 加上 $httpProvider.defaults.headers.get['DNT']='1' 可以解决GET请求,测试报错,待解决。