2014-10-07 46 views
2

我希望角度专家能够指引我朝着正确的方向发展。当使用以下格式工厂,我怎么修改POST头,因此:AngularJS,如何正确修改工厂中的http头文件

'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'? 

代码:

var tableModule = angular.module('theApp', ['ui-rangeSlider','ngScrollbar']); 

tableModule.factory('Services', ['$http', 
function($http) { 
    return { 
     get : function($path, callback) { 
      return $http.get($path).success(callback);  
     }, 
     post : function($path, $data, callback) { 
      return $http.post($path, $data).success(callback); 
     } 
    }; 
}]); 

回答

2

为什么不能简单地用第三配置参数$http.post ...

post: function(path, data) { 
    return $http.post(path, data, { 
     headers: { 
      'Content-type': 'application/x-www-form-urlencoded' 
     } 
    }); 
} 
+0

你为什么要删除回调? – nodoze 2014-10-07 02:58:26

+0

@nodoze只是习惯。我更喜欢使用承诺对象本身。我的答案的主要观点是向你展示如何传递标题 – Phil 2014-10-07 03:29:02

+1

,我认为这有窍门,谢谢菲尔。它没有解决我的大问题,但它似乎通过了头。我的大角度问题在这里:http://stackoverflow.com/questions/26226519/accessing-post-data-in-python-with-cgi-fieldstorage-using-angularjs – nodoze 2014-10-07 03:47:46

2

我想这样的事情早。该方法看起来像

$scope.update = function (user) { 
     $http({ 
      method: 'POST', 
      url: 'https://mytestserver.com/that/does/not/exists', 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded' 
      }, 
      transformRequest: function (data) { 
       var postData = []; 
       for (var prop in data) 
       postData.push(encodeURIComponent(prop) + "=" + encodeURIComponent(data[prop])); 
       return postData.join("&"); 
      }, 
      data: user 
     }); 
    } 

也看到我的小提琴http://jsfiddle.net/cmyworld/doLhmgL6/