Skip to content

Instantly share code, notes, and snippets.

@bluerabbit
Last active December 17, 2015 11:49
Show Gist options
  • Save bluerabbit/5604732 to your computer and use it in GitHub Desktop.
Save bluerabbit/5604732 to your computer and use it in GitHub Desktop.
angularjsで$http(method: 'POST', data: {})にしてもjQueryのようにパラメータが取得できない件の対応方法

方法(1)

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http({ url: '/path/to', 
        method: 'POST', 
        data: jQuery.param({name: 'hoge', age: 10})
      }).success(function (json, status) {
      });

方法(2) module global setting

  var app = angular.module('myModule', [])
                   .config(['$httpProvider', function($httpProvider) {
                       return $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
            }]);
// コントローラーでは下記のみ
$http({ url: '/path/to', 
        method: 'POST', 
        data: jQuery.param({name: 'hoge', age: 10})
      }).success(function (json, status) {
      });

参考

http://stackoverflow.com/questions/11442632/how-can-i-make-angular-js-post-data-as-form-data-instead-of-a-request-payload

@bluerabbit
Copy link
Author

なんでjQuery.param使わないといけないのさ...

gyazo

@bluerabbit
Copy link
Author

http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

transformRequestを使ってjQuery.paramとおさらばできる

$httpProvider.defaults.transformRequest = [function(data)
  {
    /**
     * The workhorse; converts an object to x-www-form-urlencoded serialization.
     * @param {Object} obj
     * @return {String}
     */ 
    var param = function(obj)
    {
      var query = '';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment