今日工作中遇到了需要從JSP傳遞對(duì)象數(shù)組到后臺(tái)的需求,網(wǎng)上輾轉(zhuǎn)找了很多資料,終于解決??嘤诰W(wǎng)上很多資料不全,故記錄下詳細(xì)解決過(guò)程。如下:
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('添加賬號(hào)失敗.');
}
}
});
}
$("#contribute_account").append(html);
}
關(guān)鍵之處有三:
一,定義數(shù)組
二,定義對(duì)象,并迭代添加對(duì)象屬性,最后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ù)組對(duì)象
data : {list : JSON.stringify(_list)}
后臺(tái)java:
/**
* 添加投稿賬號(hào)
*/
@RequestMapping(value = "addContributeAccounts")
@ResponseBody
public JsonResult addContributeAccounts(String list) {
JSONArray ary = JSONArray.fromObject(list);
if(ary != null ary.size() > 0){
ListRegionContributeAccount> accountList = (ListRegionContributeAccount>)JSONArray.toCollection(ary,
RegionContributeAccount.class);
for(RegionContributeAccount account : accountList){
companyAccountService.insertContributeAccount(account);
}
}
MapString, Object> obj = new HashMapString, Object>();
obj.put("result", 1);
return JsonResult.success(obj);
}
后臺(tái)要點(diǎn)有二,
一,轉(zhuǎn)換ary數(shù)組
JSONArray ary = JSONArray.fromObject(list);
二,數(shù)組轉(zhuǎn)自定義java對(duì)象
ListRegionContributeAccount> accountList = (ListRegionContributeAccount>)JSONArray.toCollection(ary,
RegionContributeAccount.class);
自此,便打通前后端任督二脈。
以上這篇ajax從JSP傳遞對(duì)象數(shù)組到后臺(tái)的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- jquery ajax 向后臺(tái)傳遞數(shù)組參數(shù)示例
- 使用js聲明數(shù)組,對(duì)象在jsp頁(yè)面中(獲得ajax得到j(luò)son數(shù)據(jù))
- 以JSON形式將JS中Array對(duì)象數(shù)組傳至后臺(tái)的方法
- ajax 提交數(shù)據(jù)到后臺(tái)jsp頁(yè)面及頁(yè)面跳轉(zhuǎn)問(wèn)題