0

I am trying to get array, which is created in javascript function to my java class.

In my java class this array comes as a null value.

here is my jsp code,

            <input type="button" value="Submit" onClick="submit()" />

                <script>
                    var a = "I am A"
                    var b = "I am B"
                    var c = "I am C"
                    var arr = [a,b,c];

                    function submit() {
                        $.ajax({

                            method : "POST",
                            url : 'myServlet',
                            dataType : "text/html",
                            data : {sts:arr}
                            success : function(resp) {
                            },
                            error : function(data) {
                            },
                        });
                    }

                </script>
            <!--  </form> -->
            </body>

            </html>

my java class to access the array,

            protected void doPost(HttpServletRequest request, HttpServletResponse response) {               
                String[] n=request.getParameterValues("sts");   
                System.out.println(n);
            }

also tried the following

            protected void doPost(HttpServletRequest request, HttpServletResponse response) {               
                String[] n=request.getParameterValues("sts[]");     
                System.out.println(n);
            }

both prints only null and not array.

Can anyone say where the mistake happens?

Thanks in advance.

7
  • var arr = [a,b,c]; what is a,b ,c ? Commented Dec 15, 2015 at 12:02
  • Pretty sure that a, b and c need to evaluate to something on your JS code. Commented Dec 15, 2015 at 12:02
  • They are a simple string values. Commented Dec 15, 2015 at 12:03
  • 1
    Shouldn't it be data : {"sts":arr}? Also check what gets sent by the browser using the browsers developer console, i.e. whether the array is sent at all and using which parameter name. Commented Dec 15, 2015 at 12:03
  • I updated my question Commented Dec 15, 2015 at 12:06

1 Answer 1

0

when you send arr in http request as data:{arr:arr}

check in developer console, it sending as

?arr%5B%5D=a&arr%5B%5D=b&arr%5B%5D=c

so try like this,

send arr as string

data:{arr:arr.toString()}

then in your java code get array like this,

String str = request.getParameter("arr");
String strA[] = str.split(",");

it is working....

Sign up to request clarification or add additional context in comments.

Comments