今日工作中遇到了需要從JSP傳遞對象數(shù)組到后臺的需求,網(wǎng)上輾轉(zhuǎn)找了很多資料,終于解決。苦于網(wǎng)上很多資料不全,故記錄下詳細(xì)解決過程。如下:
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); }
關(guān)鍵之處有三:
一,定義數(shù)組
var _list = new Array();
二,定義對象,并迭代添加對象屬性,最后push進(jìn)數(shù)組
var account = new Object();
account.accountId = ary[i].id; account.account = ary[i].innerHTML; _list.push(account);
三,提交時(shí)轉(zhuǎn)換數(shù)組對象
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); }
后臺要點(diǎn)有二,
一,轉(zhuǎn)換ary數(shù)組
JSONArray ary = JSONArray.fromObject(list);
二,數(shù)組轉(zhuǎn)自定義java對象
List<RegionContributeAccount> accountList = (List<RegionContributeAccount>)JSONArray.toCollection(ary, RegionContributeAccount.class);
自此,便打通前后端任督二脈。
以上這篇ajax從JSP傳遞對象數(shù)組到后臺的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com