2017-04-24 94 views
0

我想通过一些文本输入作为数组字符串到角度控制器。我能够通过使用String key = request.getParameter("key");如何将字符串数组从html输入传递给Angular http Post?

派单输入作为POST PARAM和得到它的Serlvet这是我的形式

<form ng-controller="FormController" ng-submit="submitForm()" class="ng-valid ng-scope ng-dirty ng-valid-parse">  
    <p>Text1: <input type="text" name="ancestor" ng-model="blob.ancestor" class="ng-valid ng-dirty ng-touched ng-empty"></p> 
<p>Text2: <input type="text" name="ancestor" ng-model="blob.ancestor" class="ng-valid ng-dirty ng-valid-parse ng-empty ng-touched"></p> 
<p><input type="submit" class="btn btn-primary" value="Confirm"></p> 
</form> 

,这是我的JS脚本:

var app = angular.module('myApp', []); 
app.controller('FormController', FormController); 
FormController.$inject = ['$scope', '$http', '$httpParamSerializerJQLike']; 

function FormController($scope, $http, $httpParamSerializerJQLike) { 
    $scope.blob = {}; 
    $scope.submitForm = function() { 
     alert(JSON.stringify($scope.blob)); 
     $http({ 
      method : 'POST', 
      url : '/javaAngularJS', 
      data: $httpParamSerializerJQLike($scope.blob), 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;' 
      } 
     }); 
    }; 
} 

同样,我能够发送单个参数,但我想发送具有多个值的“祖先”,并使用我的Post方法在servlet中使用String ancestors[] = reuest.getParameterValues("ancestor");

回答

0

让我们假设你从后端得到祖先的值为[1,2,3,4]作为数组。你可以将此值输入字段ng-repeat绑定这样

在控制器:

$scope.blob = {}; 
$scope.blob.ancestor = [1, 2, 3, 4]; 

在HTML:

<form ng-submit="submitForm()" class="ng-valid ng-scope ng-dirty ng-valid-parse"> 
    <p ng-repeat="ancestor in blob.ancestor">Text {{$index +1}}: <input type="text" name="ancestor" ng-model="ancestor" class="ng-valid ng-dirty ng-touched ng-empty"></p> 
    <p><input type="submit" class="btn btn-primary" value="Confirm"></p> 
</form> 

现在submitForm()点击我们将执行此将数据发送到阵列中的后端

$scope.submitForm = function() { 
    console.log($scope.blob); // result:{"ancestor":[1,2,3,4]} 
    $http({ 
     url: 'http://localhost:8080', 
     method: "POST", 
     params: { 
      ancestor: $scope.blob.ancestor 
     } 
    }).success(function(data) { 
     console.log(data); 

    }).error(function(data) { 
     console.log(data); 
    }); 
} 

数据将以参数形式发送,URL将会看起来像这样:

http://localhost:8080?ancestor=1&ancestor=2&ancestor=3&ancestor=4 
+0

thx!它为我工作。顺便说一句,我使用'.then(function successCallback(response){}'insted'.success(){}'已被弃用的Angular版本> 1.4.x –

相关问题