1.$http请求中必须添加header 并且 "Content-Type" = "application/x-www-form-urlencoded"
2.$http请求中body的数据格式必须为x=x&y=y&z=z。就是说如果我们的参数为json对象,那么必须要使用$.param() 进行序列化
不序列化请求可以成功,但是后台中参数值是接不到的,序列化后就可以成功接到值
使用$.param()进行序列化,需要引用jqueryvar defer = $q.defer();
$http( {
method: 'POST'
,params: { Account: Account ,PhoneUID:phoneUID,QutenType:pQutenType}
,data: $.param( {'name':'1','age':3})
,url: apiUrl+"Question"
,headers:{
'Content-Type':'application/x-www-form-urlencoded'
}
} ).success( function ( data )
{
defer.resolve( data );
} )
.error( function ( data, status, headers, config )
{
defer.reject();
} );
return defer.promise;
$.param是jquery中方法,如果不想使用Jquery可以使用下面的方式对参数进行序列化
在config中配置$http请求
.config(function($stateProvider, $urlRouterProvider,$ionicConfigProvider,$httpProvider) {
// Intercept POST requests, convert to standard form encoding
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj
* @return {String}
*/
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;
}];
在使用的时候就不用再处理了
var defer = $q.defer();
$http( {
method: 'POST'
,params: { Account: Account ,PhoneUID:phoneUID,QutenType:pQutenType}
,data: {'name':'1','age':3}
,url: apiUrl+"Question"
} ).success( function ( data )
{
defer.resolve( data );
} )
.error( function ( data, status, headers, config )
{
defer.reject();
} );
return defer.promise;