您必須將屬於同一事件的複選框的名稱更改爲唯一名稱。
HTML
<tr>
<td>
<input type="checkbox" name="event" value="ev1">
<td>
<input type="checkbox" name="daysA" value="Sat">
<input type="checkbox" name="daysA" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev2">
<td>
<input type="checkbox" name="daysB" value="Fri">
<input type="checkbox" name="daysB" value="Sat">
<input type="checkbox" name="daysB" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev3">
<td>
<input type="checkbox" name="daysC" value="Sat">
<input type="checkbox" name="daysC" value="Sun">
<input type="checkbox" name="daysC" value="Mon">
腳本
var events = [];
var daysA = [];
var daysB = [];
var daysC = [];
var jsonData="";
function c(){
var eventCB = document.getElementsByName("event");
var daysACB = document.getElementsByName("daysA");
var daysBCB = document.getElementsByName("daysB");
var daysCCB = document.getElementsByName("daysC");
for(var i=0;i<eventCB.length;++i){
events.push(eventCB[i].value);
}
for(var i=0;i<daysACB.length;++i){
daysA.push(daysACB[i].value);
}
for(var i=0;i<daysBCB.length;++i){
daysB.push(daysBCB[i].value);
}
for(var i=0;i<daysCCB.length;++i){
daysC.push(daysCCB[i].value);
}
jsonData ='{events:['+events.toString()+'],days:[['+daysA.toString()+'],['+daysB.toString()+'],['+daysC.toString()+']]}'
}
將數據傳遞到Servlet的
var jsonComplete = JSON.stringify(jsonData);//You will get below string
//{events:[ev1,ev2,ev3],days:[[Sat,Sun],[Fri,Sat,Sun],[Sat,Sun,Mon]]}
$.ajax({
url:"URLServlet",
type:"POST",
dataType:'json',
data: {jsonComplete : jsonComplete },
success:function(data){
// do whatever required
},
});
在Servlet的接收數據使用org.json
JSONObject objJSON = new JSONObject(request.getParameter("jsonComplete "));
JSONArray arrEvents = objJSON.getJSONArray("events");
JSONArray arrDays = objJSON.getJSONArray("days");
for(int i=0;i<arrEvents.length();++i){
out.println("event["+i+"]:"+arrEvents.getString(i));//Similar to event[0]:ev1
}
for(int i=0;i<arrDays.length();++i){
JSONArray arrDaystemp = arrDays.getJSONArray(i);
out.println("days["+i+"]:[");
for(int i=0;i<arrDaystemp.length();++i){
out.println(arrDaystemp.getString(i));//Similar to days[0]:[Mon,Tue]
}
out.println("]");
}
不知道Java,但在PHP中,你會複選框名稱後加括號,使數組名=「天[]」 – Billy 2014-11-24 22:37:10
@Billy在Java中你不需要它,它對於如何創建二維數組仍然沒有幫助。 – developerwjk 2014-11-24 23:12:15