2015-05-18 42 views
1

以下代碼將表單數據作爲json而不是鍵值對發佈。

服務

  $resource(apiPath, { 
       Id: '@Id', 
       apt_id: user_info.apt_id, 
       mauth_token: user_info.mauth_token, 
       mauth_account_id: user_info.mauth_acnt_id, 
       rest: 1, 
      }, { 
       save:{ 
        method:'POST', 
        headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
       } 
      }); 

控制器

.controller('BroadcastSmsSendCtrl', function($scope, $ionicLoading, $ionicActionSheet, $state, $timeout, $location, BroadcastSmsSvcs, GetUserCountHttpSvcs) { 
      $scope.entry = new BroadcastSmsSvcs(); 

      $scope.doSubmit = function() { 
       BroadcastSmsSvcs.save({}, $scope.entry); 
      }; 
     }); 

Form data

回答

3

添加在您的.config()功能如下

$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; 
$httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) { 
    var key, result = [], response; 
    if(typeof data == "string") { //$http support 
      response = data; 
    } else { 
      for (key in data) { 
       if (data.hasOwnProperty(key)) { 
        result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key])); 
       } 
      } 
      response = result.join("&"); 
     } 
     return response; 
}); 
3

嘗試添加以下內容到$資源對象

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("&"); 
    } 
    } 
12

AngularJs提供了轉變爲像jQuery的序列化對象服務。

而是JSON序列化的:{"id": 1, "name": "whatever"}

它變成:id=1&name=whatever

那麼簡單,你可以這樣做:

save:{ 
    method: "POST", 
    headers : {"Content-Type": "application/x-www-form-urlencoded"}, 
    transformRequest: function(data) { 
     return $httpParamSerializerJQLike(data); 
    } 
} 

注意:在你的服務,你必須注入$httpParamSerializerJQLike服務