How to send JavaScript array to Servlet inside form tag?

我只是一个虾纸丫 提交于 2019-12-13 07:15:52

问题


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">&nbsp;<%= 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">&nbsp;<%= 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,

  1. Create a hidden field inside the form,
  2. Convert Javascript array to a comma/pipe separated string, (example 1, 2)
  3. Set the value of the hidden field to this string, (example here)
  4. This way, when you submit the form, the hidden field data is also sent to server,
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!