赞
踩
平常我们在写ajax异步请求发送参数给后台时,参数一般都是String类型,但是有时候我们需要传递集合对象到后台,那我们应该怎么写呢
格式如下:
- var _list = {};
-
- for (var i = 0; i < 10; i++) {
- _list["后台controller中的接收名字[" + i + "]"] = 值;
- }
-
- $.ajax({
- url: '传递的路径',
- data: _list, //直接传_list节可以了,相当于 data: { "ids[0]":1,"ids[1]":2 }这种写法
- dataType: "json",
- type: "POST",
- success: function (data) {
- alert('Ok');
- }
- });
function saveData(){
var siteList = {};
var alarmList = {}
var i = 0;
$("tr").each(function(){
var isAarmList = {};
var siteArrTemp = [];
var isAarmArrTemp = [];
var j = 0;
$(this).children('td').children('input[type=checkbox]:checked').each(function(index,item){
var siteId = item.id;
var alarmLevelName = item.name;
siteArrTemp.push(siteId);
isAarmList[j] = alarmLevelName;
isAarmArrTemp.push(alarmLevelName);
j++;
});
if(isAarmArrTemp.length>0){
alarmList[i] = isAarmList;
}
if(siteArrTemp.length>0){
siteList[i]= siteArrTemp[0];
i ++ ;
}
});
var param = {
userId: siteTreeCreator.curNode().id,
siteId : siteList,
alrmLevels: alarmList
};
$.post(contextPath + '/alarm/notice/saveUserGetAlarm.do?', param, function(data) {
if(data.flag == true) {
tip.show("保存成功!", 0, 1500);
} else {
tip.show(data.message, 1, 1500);
}
})
}
从上面的代码我们可以看出,param里面的userId为String类型的,siteList为list类型的,而alrmLevels为list<List>类型的
@RequestMapping("/saveUserGetAlarm")
@ResponseBody
public List<Map<String,Object>> saveUserGetAlarm(AlarmNoticeOfGetDataVo alarmNoticeOfGetDataVo) {
List<Map<String,Object>> userAlarmSites = new ArrayList<Map<String,Object>>();
//获取人员
String userId = alarmNoticeOfGetDataVo.getUserId();
//获取配置的站点id
List<String> sites = alarmNoticeOfGetDataVo.getSiteId();
//获取配置的级别
List<List<String>> siteAlarms = alarmNoticeOfGetDataVo.getAlrmLevels();
return userAlarmSites;
}
我们统一用AlarmNoticeOfGetDataVo对象来接收参数,我们现在来看AlarmNoticeOfGetDataVo对象
public class AlarmNoticeOfGetDataVo {
private String userId;
private List<String> siteId;
private List<List<String>> alrmLevels;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<String> getSiteId() {
return siteId;
}
public void setSiteId(List<String> siteId) {
this.siteId = siteId;
}
public List<List<String>> getAlrmLevels() {
return alrmLevels;
}
public void setAlrmLevels(List<List<String>> alrmLevels) {
this.alrmLevels = alrmLevels;
}
从以上代码我们可以看出,实体里的属性和js传递来的属性是一一对应的,这样js的param就相当于AlarmNoticeOfGetDataVo对象,而param里的参数则相当于AlarmNoticeOfGetDataVo的属性,需要注意的是,参数一定要和后台的属性名一致,否则传递不成功。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。