如何将表单值传递给Angular脚本,并从脚本传递给Spring MVC控制器。下面我编写了表单数据无法发送控制器的代码
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController',[ '$scope', '$http', function($scope, $http) {
$scope.list = [];
$scope.headerText = 'AngularJS Post Form Spring MVC example: Submit below form';
$scope.formData = {};
$scope.submit = function() {
var formData = {
"name" : $scope.name,
"salary" : $scope.salary,
"designation" : $scope.designation,
};
var response = $http.post('submitmock',{ Emp: formData}); //passing Emp
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});
response.error(function(data, status, headers, config) {
alert("Exception details: " + JSON.stringify({
data: $scope.formData //used formData model here
}));
});
//Empty list data after process
$scope.list = [];
};
}]);
@RequestMapping(value = "submitmock", method = RequestMethod.POST)
public @ResponseBody Emp getMock(@RequestBody Emp Emp)
{
serviceInD.savedata(Emp);
return Emp;
}
答案 0 :(得分:1)
也许你需要在你的春季MVC中允许交叉起源
像那样:@CrossOrigin
@RequestMapping(value = "submitmock", method = RequestMethod.POST)
public @ResponseBody Emp getMock(@RequestBody Emp Emp)
{
serviceInD.savedata(Emp);
return Emp;
}
您可以参考弹簧指南: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors-controller
答案 1 :(得分:0)
您需要在http帖子中指明发送给控制器的数据类型。 您可以在请求中指定带标题的类型:
var response = $http.post('submitmock', { Emp: formData}, {headers:{'Content-Type': 'application/json'}});
答案 2 :(得分:0)
你的formData已经是body,不需要用Emp映射。尝试替换脚本文件中的以下代码
var response = $http.post('submitmock', formData); //passing Emp
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});