Pass array of data from Angular $http POST

后端 未结 4 1112
忘掉有多难
忘掉有多难 2020-12-28 15:46

I need to pass an array of object from my Angular application to a .Net web service with Nancy framework.

I tried this :

function TestCtrl($scope, $         


        
相关标签:
4条回答
  • 2020-12-28 15:54

    you can use $httpParamSerializer or $httpParamSerializerJQLike

    $http(
        url: 'myURL',
        method: "POST",
        data: $httpParamSerializer(data),
    )
    
    0 讨论(0)
  • 2020-12-28 16:05

    fauverism is right, you can use angular.toJson(data). Not instead, but before $.param though.

    function TestCtrl($scope, $http){
    $scope.postTest = function(){
    
        var data = [obj1, obj2, obj3];
        var jsonData=angular.toJson(data);
        var objectToSerialize={'object':jsonData};
    
        $http({
            url: 'myURL',
            method: "POST",
            data: $.param(objectToSerialize),
            headers: {
                     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).success(function(data){
            alert("done");
        });
    }
    

    }

    0 讨论(0)
  • angular.toJson(data)
    

    should work in place of

    $.param(data)
    
    0 讨论(0)
  • 2020-12-28 16:17

    According to this post, you're right, this is about serialization. Angular doesn't automatic serialize the data for you, you need to parse the data before sending it:

    ...
    
    $http({
      url: 'myURL',
      method: "POST",
      data: $.param(data),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })...
    

    If you don't use jQuery, you'll need to roll your own $.parse. There is a snippet here or you could adapt jQuery implementation.

    0 讨论(0)
提交回复
热议问题