问题
I have made checkbox code and on checkbox click I am calling function which will add passed argument to JavaScript array. I have taken form tag inside body and inside form tag there is only checkboxes and a button. On button click servlet will called so I want some mechanism that will also send Java Script array data to servlet with checkbox value.
onClick of checkbox I am not passing checkbox value, I am passing other details so need other function to add data in array and pass it to servlet.
checkbox code :
<input type="checkbox" id="demo_box_2<%= aname %><%= aval %><%=k %>" class="css-checkbox" name="configcheckbox" value="<%= aval %>" onchange="addcategory('<%= acid %>')">
<label for="demo_box_2<%= aname %><%= aval %><%=k %>" name="demo_lbl_2<%=k %>" class="css-label"> <%= aval %></label>
JavaScript function :
var acdata = [];
function addcategory(acid)
{
acdata.push(acid);
//alert(acid);
}
the code of checkbox is inside form tag, so I also want to send acdata[] array with checkbox value to servlet, so any help please ?
回答1:
Here is sample code as Santosh explained,
In your script (Edited),
var acdata = [];
function addcategory(acid)
{
acdata.push(acid);
$("#hidden_array").val(acdata);
}
In your html,
<input type="checkbox" id="demo_box_2<%= aname %><%= aval %><%=k %>"
class="css-checkbox"
name="configcheckbox" value="<%= aval %>" onchange="addcategory('<%= acid %>')">
<label for="demo_box_2<%= aname %><%= aval %><%=k %>" name="demo_lbl_2<%=k %>"
class="css-label"> <%= aval %></label>
With this add one more hidden field inside your form like this,
<input type="hidden" id="hidden_array" name="hiddenArray" >
Hence you can get the array values in your jsp/servlet like this,
request.getParameterValues("hiddenArray");
PS: You can use string array String[] to process your data.
回答2:
Here is one way to achieve this,
- Create a hidden field inside the form,
- Convert Javascript array to a comma/pipe separated string, (example 1, 2)
- Set the value of the hidden field to this string, (example here)
- This way, when you submit the form, the hidden field data is also sent to server,
- On the server side, split the string to get the data back as array of Java strings.
来源:https://stackoverflow.com/questions/20561249/how-to-send-javascript-array-to-servlet-inside-form-tag