这里有新鲜出炉的 AngularJS Tutorial 中文版,程序狗速度看过来!
AngularJS 诞生于 Google 是一款优秀的前端 JS 框架,已经被用于 Google 的多款产品当中。AngularJS 有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、语义化标签、依赖注入,等等。
这篇文章主要给大家介绍了关于 Angular.js 前台传 list 数组之后,由后台 spring MVC 接收数组的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
前言
本文主要给大家介绍了关于 Angular.js 前台传 list 数组由后台 spring MVC 接收数组的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍吧。
在开发中有时候需要在前台自定义对象,然后把对象封装在 list 中,在传送到后台,这样的思想也比较合理,直接来看示例代码:
1. 前台代码
- $scope.saveScore = function () {
- $scope.userScoreList = new Array();//自定义数组
- angular.forEach ($scope.records, function (record, index) {
- if (record.score != null) {
- $scope.userScoreModel = {'userAnswerId': null,'score': null};//自定义对象结构
- $scope.userScoreModel.userAnswerId = record.userAnswerId;//赋值
- $scope.userScoreModel.score = record.score;
- $scope.userScoreList.push($scope.userScoreModel);//把对象封装在集合中
- debugger;
- }
- });
- if ($scope.userScoreList != null && $scope.userScoreList.length > 0) {
- var fd = new FormData();// 使用angularJS的FormData封装要传送的数据
- var userScoreRecords = angular.toJson($scope.userScoreList);//把对象(集合)转换为json串
- fd.append('userScoreRecords', userScoreRecords);//参数放入formData中
- debugger;//使用 debugger模式查看传值情况
- $http.post('/reviewProcess/save', fd, { //使用post方法 传送formdata对象
- transformRequest: angular.identity, //使用angular传参认证
- headers: {
- 'Content-Type': undefined //设置请求头
- }
- })
- .success(function (data){
- toastr.success("success");
- })
- .error(function (data) {
- toastr.success("failed");
- });
- }
- };
2. 后台接收
- @ResponseBody
- @RequestMapping(value = "/reviewProcess/save", method = RequestMethod.POST)
- public void saveUserScore (@RequestParam("userScoreRecords") String userScoreRecords) { //使用requestparam接收前台传送的json串
- System.out.println(userScoreRecords);
- ObjectMapper mapper = new ObjectMapper(); // 使用fastJson的ObjectMapper反序列化json串为对象
- UserScoreModel record = null;
- try {
- JSONArray jsonArray = new JSONArray (userScoreRecords); //在后台把json串转换为json数组
- for (int i =0; i < jsonArray.length(); i++) {
- record = mapper.readValue(jsonArray.getJSONObject(i).toString(), UserScoreModel.class); //获取json数组的json对象并且反序列化为对应的对象
- System.out.println(record); // 得到对象后后台即可操作
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- }
总结
来源: http://www.phperz.com/article/17/0811/343920.html