0

My question is

how to read javascript array from servlet

Using javascript, I am reading the creating the ArrayList as follows:

var data1= new Array();
for(var i=1;i<=count;i++){
    var Obj=new Object();
    Obj.Name=$('#name'+i).val();
    Obj.url=$('#empno'+i).val();
    data1.push(""+Obj);
}
$.post("servlet", {'array':data1,mode:"insert" }); 

From servlet how to read the values

String[] data=request.getParameterValues("array[]");
Asha Datla
  • 126
  • 1
  • 11
  • Have a look at this: http://stackoverflow.com/questions/13241668/how-to-send-array-to-servlet-using-jquery-ajax – Sas Aug 23 '14 at 15:11
  • From servlet with the following code i reading the arraylist String[] data=request.getParameterValues("array[]"); Sytem.out.println("------"data[0]); it is printing [object object] Pls suggest how to get the name and url in the array – Asha Datla Aug 24 '14 at 02:41

2 Answers2

0

You can get parameters from the request

String array = request.getParameter("array");
String mode= request.getParameter("mode");
0

Try using "Json.stringify".

$.ajax({
        url: 'http://localhost:8080/JasonToServlet/test',
        type: 'POST', 
        dataType: 'json',
        data: {"json[]": JSON.stringify(data1)},
        success: function(result) {
        }
   });

This will parse the array as string as follows:

 [{"Name":"Test","url":"Me"},{"Name":"Test2","url":"Me2"}]

The problem here is that above result is a string not an array. So you gonna have to use stringtokenizer to split the string and make it as array.

From servlet get this as:

String row= request.getParameter("json[]");
String row1= request.getParameter("mode");
StringTokenizer str = new StringTokenizer(row, "[{}]");
List<String> temp = new ArrayList<String>();

while (str.hasMoreElements()) {
    String token = str.nextToken(); 
    if(!token.equal(","))
        temp.add(token);
}

THIS IS NOT A PERFECT SOLUTION, BUT IT WORKS.. :)

Sas
  • 2,473
  • 6
  • 30
  • 47