最近遇到前台通过ajax传数组参数到后台的问题,在网上查了很多解决办法都不好用,最终我还是找到了一种解决办法。
我决定分享出来,让正确的解决方案多些。方便查找。
首先前台对象为我拼的数组,数组元素是对象。
js代码:
数组结构为 mapArr:[{'id':1,'name':'h1'},{'id':2,'name':'h2'},{'id':3,'name':'h'3}]
function updateAjax() {
$.ajax({
type : "POST",
data : {
'mapArr' : JSON.stringify(sortData.mapArr),/ /JSON传数组格式
},
url : "Map_SortAjaxAction!updateList",
dataType : 'json',
beforeSend : function(XMLHttpRequest) {},
success : function(data) {
sortData.trafficArr=[];
sortData.trafficArr=[];
}
})
}
前台需要用JSON.stringify()方法,顺便说下JSON.parse()和JSON.stringify()的作用
parse用于从一个字符串中解析出json对象,stringify()用于从一个对象解析出字符串
后台 struts的action接收:
private String mapArr;
public String getMapArr() {
return mapArr;
}
public void setMapArr(String mapArr) {
this.mapArr = mapArr;
}
public String updateList() throws SystemException {
JSONObject jsonObject = new JSONObject();
JSONArray mapArray = JSONArray.fromObject(mapArr);
List<TermapDTO>maplist=(List<TermapDTO>)JSONArray.toCollection(mapArray,TermapDTO.class);
for(MTermapMappingDTO termapMapping : maplist){
maptraffic_Sort_Service.updateMapping(termapMapping);
}
return SUCCESS;
}