jquery将前台选中的checkbox值以数组形式发送到后台struts的action

本文介绍如何在Struts框架中从前台通过Checkbox选择项以数组形式传递到后台,并展示具体的实现代码,包括使用jQuery进行AJAX请求以及后台Action处理逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的需求是将前台页面选中的checkbox的value值以数组发送到后台,我的后台使用struts的action接收参数。
前台页面如下:

<input type="checkbox" name="idList" value='1'/>
<input type="checkbox" name="idList" value='2'/>
<input type="checkbox" name="idList" value='3'/>
<input type="checkbox" name="idList" value='4'/>

要以数组的形式发送数据就需要input的name属性值设置为相同。而后台struts的action使用List来接收前台传来的参数。
前台向struts的action传递数组的格式如:

idList=1&idList=2&idList=3

或以json传递:

{idList:1,idList:2,idList:3}

如果我想将id为1、2、3的email删除,使用jquery的ajax方法如下:

$.post("deleteEmails.action","idList=1&idList=2&idList=3",function(result){
$(".content-box-content").html(result);
});


那么如果是想将前台选中的email删除,那么只需要将选中的checkbox的name和value拼接成上述格式就行了。

如下:

var selectedItems = new Array();
$("input[@name='idList']:checked").each(function(){
selectedItems.push("idList="+$(this).val());
});
$.post("deleteEmails.action",selectedItems.join("&"),function(result){
$(".content-box-content").html(result);
});



jquery还为我们提供一个更简单的方法,既是使用serialize或serializeArray,这两个方法通常用在表单上,这里使用serialize将大大减少代码,如下:

$.post("deleteEmails.action",$("input[@name='idList']:checked").serialize(),function(result){
$(".content-box-content").html(result);
});


我的后台action如下:


@Scope("prototype")
@Controller("emailAction")
public class EmailAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = -2943423285236995103L;
@Autowired
private EmailService emailService;

static Logger log = Logger.getLogger(EmailAction.class);
public EmailService getEmailService() {
return emailService;
}
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}

private List<Integer> idList;

public List<Integer> getIdList() {
return idList;
}
public void setIdList(List<Integer> idList) {
this.idList = idList;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public String deleteEmails(){
Map request = (Map) ActionContext.getContext().get("request");
if(idList == null){
request.put("type", "error");
request.put("tip", "删除出现错误,删除失败!");
return ERROR;
}
for(int id : idList){
if(!this.emailService.deleteEmailById(id)){
request.put("type", "error");
request.put("tip", "删除出现错误,删除失败!");
return ERROR;
}
}
request.put("type", "success");
request.put("tip", "删除成功!");
return SUCCESS;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值