前台代码如下:获取单选和多选的值,将所需的值放到放到页面创建的json中,传递到后台。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>页面创建json传递到后台</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
function toDemo(){
//创建json数组
var jsonstr="[]";
//使用eval方式解析
var jsonarray = eval('('+jsonstr+')');
var str='';
//所有td个数
var length = $("table td").size();
//创建数组
var arr = [];
for(var index = 0;index<length;index ++){
arr[index] = index;
}
//将id和选中的值循环放到json数组里
$.each(arr, function(i){
//循环得到不同的td的id值
var idValue = $("table td").eq(i).attr("id");
//判断在该td下里的input是单选还是多选
var pandan = $('#'+idValue +' '+'input').eq(0).attr("type");
if(pandan =='radio'){
//每个td下的已选中的单选框的值
var ra1= $('#'+idValue +' '+'input:radio:checked').val();
//将选中的值和id放到json中
var arr =
{
"Id" : idValue,
"Key" : ra1
}
jsonarray.push(arr);
}else if(pandan =='checkbox'){
//每个td下的已选中的多选框的值
var strcheckbox = '';
$('#'+idValue +' '+'input[type="checkbox"]').each(function(){
if ($(this).is(':checked') ) {
var chestr = $(this).val();
strcheckbox+=chestr+',';
}
});
strcheckbox=strcheckbox.substring(0,strcheckbox.length-1)
//将选中的值和id放到json中
var arr2 =
{
"Id" : idValue,
"Key" : strcheckbox
}
jsonarray.push(arr2);
}
});
//JSON对象序列化成JSON字符串,使用浏览器自带的JSON对象中的JSON.stringify方法
var str = JSON.stringify(jsonarray);
//alert(str);
<span style="white-space:pre"> </span>$("#getJson").val(str);
}
</script>
</head>
<body>
<input type="hidden" id="getJson" />
<form>
<table>
<tr>
<td id="d1">
111:<input type="radio" id="a1" name="r1" value="a1"/>1
<input type="radio" id="a2" name="r1" value="a2"/>2
<td>
</tr>
<tr>
<td id="d2">
222:<input type="radio" id="a3" name="r2" value="a3"/>3
<input type="radio" id="a4" name="r2" value="a4"/>4
<td>
</tr>
<tr>
<td id="d3">
333:<input type="radio" id="a5" name="r3" value="a5"/>5
<input type="radio" id="a6" name="r3" value="a5"/>6
<td>
</tr>
<tr>
<td id="d4">
444:<input type="checkbox" id="a7" name="r4" value="a7"/>7
<input type="checkbox" id="a8" name="r4" value="a8"/>8
<input type="checkbox" id="a9" name="r4" value="a9"/>9
<input type="checkbox" id="a10" name="r4" value="a10"/>10
<input type="checkbox" id="a11" name="r4" value="a11"/>11
<input type="checkbox" id="a12" name="r4" value="a12"/>12
<td>
</tr>
<tr>
<td id="d5">
555:<input type="radio" id="a13" name="r5" value="a13"/>13
<input type="radio" id="a14" name="r5" value="a14"/>14
<td>
</tr>
</table>
</form>
<input type="button" id="a15" value="submit" οnclick="toDemo()">
</body>
</html>
后台用fastjson解析:fastjson下载地址
//获取json
String getJsonStr = request.getParameter("getJson");
//将json放入自己list
List<myBean> getList=JSON.parseArray(getJsonStr , myBean.class);
需要注意:本例子中json里的 “Id”,“Key”均与myBean对应。