`

jquery ajax array checkbox action

阅读更多
直接使用jquery的$.ajax()异步提交时,如果data中含有Array(如提交checkbox时),action不能直接使用List接收array。

html:
<input type="checkbox" name="id" value="1">
<input type="checkbox" name="id" value="2">
<input type="checkbox" name="id" value="13">
<input type="checkbox" name="id" value="14">

js:
$("input[type='checkbox'][name='id']:checked").each(function(){
id.push($(this).val());

});
$.ajax({
type:"post",
url:"teacherDisable.action",
dataType:"json",
success:function(data){
if(data.success == true){
alert(data.message);
window.location.reload();
}else{
alert(data.message);
}
},
data:{id:id}
});
浏览器显示提交数据:
参数application/x-www-form-urlencoded
id[] 13
id[] 14
源代码
id%5B%5D=13&id%5B%5D=14
但是后台接收变量List<Integer>  id为空

解决方案
1:data:{id:id}改为data:$.param({id:id},true),对参数进行序列化
2:改变js接收id的方法,将id转化为字符串
$("input[type='checkbox'][name='id']:checked").each(function(){
id += "id=" + $(this).val() + "&";
});
3:改变html中checkbox的name
<input type="checkbox" name="id[0]" value="1">
<input type="checkbox" name="id[1]" value="2">
<input type="checkbox" name="id[2]" value="13">
<input type="checkbox" name="id[3]" value="14">

$.ajax()改为简洁的$.post():
$.post("teacherDisable.action",$("input[type='checkbox']:checked"),function(data){
if(data.success == true){
alert(data.message);
window.location.reload();
}else{
alert(data.message);
}
});

三种方法都可以使action通过set()方法获取参数,第一种最为方便,对参数进行序列化即可,第二种方法比较简陋,将checkbox的值拼装为字符串,第三种需要更改html中checkbox的name,而且如果只选中id[3],那么后台得到的是一个长度为4的List,其中0~2为null,只有第三个有值
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics