AngularJs初探--让AngularJS的$http 服务像jQuery.ajax()一样工
最近着手开发一个后台系统,前端采用的是AngularJs来与后台交互,对于我们这群jquery疯狂的铁粉,遇到了不少转不过弯的问题,为了更高效的开发应用,在私下的时间收集和改造了一下AngularJS的$http 服务,特此分享。 $http的post jQuery.post 解决思路: 1.改造前端 (1)方案一:
配置$http服务的默认content-Type=application/x-www-form-urlencoded,如果是指配置这个的话,虽然提交的content-Type改了,但是提交的数据依然是个json字符串,不是我们想要的form data形式的键值对,需要实现param方法. angular.module('MyModule',[],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; }; //一个function数组,负责将请求的body,也就是post data,转换成想要的形式 // Override $http service's default transformRequest $httpProvider.defaults.transformRequest = [function(data) { return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; }]; }); 配合一点$resource的API参考,这个代码就好懂了: Note: 方案二: $scope.formData = {}; $http({ method: 'POST',url: '/user/',data: $.param($scope.formData),// pass in data as strings headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload) }) .success(function(data) { console.log(data); if (!data.success) { // if not successful,bind errors to error variables $scope.errorName = data.errors.name; $scope.errorSuperhero = data.errors.superheroAlias; } else { // if successful,bind success message to message $scope.message = data.message; } }); 参考 2.后端使用注意: (1)Spring MVC ajax后台方法不能加@RequestBody ,否则会报Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)错误 (2)使用Jquery 风格的写法就OK啦! 万事搞定,只欠高效开发,O(∩_∩)O哈哈~ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |