昨天我在办公桌上结束了前端任务,由于前端开发人员正在休年假,因此我需要一些帮助。
我有这个AngularJs脚本,它是我的角度控制器的一部分。我试图将一些数据发布到服务器,该数据是从多步骤向导表单中获取的。在服务器端,我已经实现了(我是一个后端开发者),所以那里没有什么让人害怕的,但是在尝试POST之前,我需要对JSON对象进行某种调整,以便可以与Spring Boot Rest Controller很好地绑定。
那就是代码。
//These are my guys which I am trying to push
$scope.department = {};
$scope.user1 = {};
$scope.user2 = {};
//Some POST method
$scope.save = function () {
var data = [{}];
//here I do the push but it looks like I've no idea what I am doing
data.push($scope.department);
data.push($scope.user1);
data.push($scope.user2);
var config = {
headers : {
'Content-Type': 'application/json'
}
}
console.log(JSON.stringify(data));
$http.post('http://localhost:8080/api/', data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
.error(function (data, status, header, config) {
console.log(data);
});
};
这是我通过上述脚本实现的JSON输出
[
{
"department": "foo",
"code": 1234
},
{
"firstName": "Megan",
"lastName": "Fox"
},
{
"firstName": "Margot",
"lastName": "Robbie"
}
]
这是我正在寻找的JSON输出
{
"department": "foo",
"code": 1234,
"user1": {
"firstName": "Megan",
"lastName": "Fox"
},
"user2": {
"firstName": "Margot",
"lastName": "Robbie"
}
}
谢谢!!!
我能够复制您的JSON,能否验证其正确性?
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope, $http) {
//These are my guys which I am trying to push
$scope.department = {
"department": "foo",
"code": 1234
};
$scope.user1 = {
"firstName": "Megan",
"lastName": "Fox"
};
$scope.user2 = {
"firstName": "Margot",
"lastName": "Robbie"
};
//Some POST method
$scope.save = function() {
var data = Object.assign({}, $scope.department);
//here I do the push but it looks like I've no idea what I am doing
data["user1"] = $scope.user1;
data["user2"] = $scope.user2;
var config = {
headers: {
'Content-Type': 'application/json'
}
}
console.log(JSON.stringify(data));
$http.post('http://localhost:8080/api/', data, config)
.success(function(data, status, headers, config) {
$scope.PostDataResponse = data;
})
.error(function(data, status, header, config) {
//console.log(data);
});
};
$scope.save();
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句