0

How to pass array as ajax request data and how to access it in servlet?

var a=[0,1,2,3];
 $.ajax({
                type: "GET",
                 url: "/accessarray",                    
                    data: { param:a},
                 success: function(data) {$('#results').html("success");
                }
            });
Arun Kumar
  • 116
  • 2
  • 4

1 Answers1

0

pass your array like this:

var myArr = [1, 2, 3, 4];

$.ajax({
  type: "POST",
  url: "YOUR SERVLET NAME",
  data: "{myArr: " + myArr + "}", 
  // what ever the data you need to pass to server to generate yout "String"

  success: function(result) {

    console.log(result);
  },
  error: function(error) {

    console.log("error" + error);
  }
});

inside the Servlet, try to get your values as a String array:

String[] myArr = request.getParameterValues('myArr');

If you need to access it as an integer array, just loop the myArr and assign the values into new int array by parsing as Integer.parseInt(myArr[index]);

hope this will help you !

Nomesh DeSilva
  • 1,649
  • 4
  • 25
  • 43