本篇文章为大家展示了使用ajax怎么从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" >';html += '<span data-id="">'+ary[i].innerHTML+'</span>';html += '<a onclick="deleteAccount(this);" href="javascript:;" rel="external nofollow" class="js-btn-remove-tag ml4" 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")@ResponseBodypublic 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传递对象数组到后台,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注编程网行业资讯频道。