ajax從JSP傳遞物件陣列到後臺

韓師學子--胖佳發表於2019-03-17

                    ajax從JSP傳遞物件陣列到後臺


轉載:https://blog.csdn.net/ruoxuan25/article/details/77530928

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:;" 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);


 

相關文章