angularjs $http请求数据序列化

文章参考 

http://blog.csdn.net/yy374864125/article/details/41113643

http://blog.johnsonlu.org/angularjs-ajax/

事件:$http发送post请求,后台获取不到前端提交的数据

原因:

由於 AngularJS 的 POST 預設用的 Content-Type 是 application/json;charset=utf-8,而且也不會對資料做serialize的處理,如果直接使用後端會抓不到 POST 的資料

解决办法1 —— 使用jquery:

解决办法2 —— 自己序列化:

var app = angular.module("sqhApp",["ionic"], function($httpProvider) {
	// Use x-www-form-urlencoded Content-Type
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

	/**
	 * 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;
	}];
});

 ------------------------------------------------其他知识点--------------------------------------------------------

 $http 发送请求的模板

$http({  
   method: string,  
   url: string,  
   params: object,  
   data: string or object,  
   headers: object,  
   transformRequest: function transform(data, headersGetter) or an array of functions,  
   transformResponse: function transform(data, headersGetter) or an array of functions,  
   cache: boolean or Cache object,  
   timeout: number,  
   withCredentials: boolean  
});

示例(发送headers请求):

$http.get('api/user', {
     //设置Authorization(授权)头。在真实的应用中,你需要到一个服务里面去获取auth令牌
     headers: {'Authorization': 'Basic Qzsda231231'},
     params: {id:5}
}).success(function() {//处理成功的情况 });

相关推荐