时间:2021-07-01 10:21:17 帮助过:11人阅读
今日工作中遇到了需要从JSP传递对象数组到后台的需求,网上辗转找了很多资料,终于解决。苦于网上很多资料不全,故记录下详细解决过程。如下:
JSP:
function addAccount(){ debugger; var html = ''; var ary = $("#match_account").find("p"); var _list = new Array(); if(ary.length){ for(var i = 0,len = ary.length;i < len;i ++){ var account = new Object(); html += '<li class="fl mb8" data-id="'+ary[i].id+'" data-sort="0">'; html += '<span class="mr8 display-ib" style="background:#eee;padding:0px 5px 6px 5px">'; html += '<span data-id="">'+ary[i].innerHTML+'</span>'; html += '<a onclick="deleteAccount(this);" href="javascript:;" rel="external nofollow" class="js-btn-remove-tag ml4" style="vertical-align:5px;color:#999;" title="删除">x</a>'; html += '</span>'; html += '</li>'; account.accountId = ary[i].id; account.account = ary[i].innerHTML; _list.push(account); } $.ajax({ type: "post", url: "${ctx}/companyAccount/addContributeAccounts", data : {list : JSON.stringify(_list)}, async: false, success: function (json) { var result = json.obj.result; if(result != 1){ layer.error('添加账号失败.'); } } }); } $("#contribute_account").append(html); }
关键之处有三:
一,定义数组
var _list = new Array();
二,定义对象,并迭代添加对象属性,最后push进数组
var account = new Object();
account.accountId = ary[i].id; account.account = ary[i].innerHTML; _list.push(account);
三,提交时转换数组对象
data : {list : JSON.stringify(_list)}
后台java:
/** * 添加投稿账号 */ @RequestMapping(value = "addContributeAccounts") @ResponseBody public JsonResult addContributeAccounts(String list) { JSONArray ary = JSONArray.fromObject(list); if(ary != null && ary.size() > 0){ List<RegionContributeAccount> accountList = (List<RegionContributeAccount>)JSONArray.toCollection(ary, RegionContributeAccount.class); for(RegionContributeAccount account : accountList){ companyAccountService.insertContributeAccount(account); } } Map<String, Object> obj = new HashMap<String, Object>(); obj.put("result", 1); return JsonResult.success(obj); }
后台要点有二,
一,转换ary数组
JSONArray ary = JSONArray.fromObject(list);
二,数组转自定义java对象
List<RegionContributeAccount> accountList = (List<RegionContributeAccount>)JSONArray.toCollection(ary, RegionContributeAccount.class);
自此,便打通前后端任督二脉。
以上这篇ajax从JSP传递对象数组到后台的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。