我的需求是将前台页面选中的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; } }