angularJS 利用 service 封装 POST 请求
angular.module('app',[]).service('postService',function($http){ return { postRequset:function(url,obj,succCallBack,errorCallBack){ return $http({ method:'post', url:url, data:obj || {}, headers:{'Content-Type':'application/x-www-form-urlencoded'}, transformRequest:function(obj){ var str = []; for(var p in obj ){ str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]); } return str.join('&'); } }) .success(function(data){ succCallBack && succCallBack(data); }).error(function(data){ errorCallBack && errorCallBack(data); }) } } })
以下为重点:
headers:{'Content-Type':'application/x-www-form-urlencoded'},
transformRequest:function(obj){
var str = [];
for(var p in obj ){
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]);
}
return str.join('&');
}
调用方法如下:
postService.postRequest('url的地址','data数据',function(data){ console.log(data); })