Send and get array of arrays js in servlet

3

I want to send an array of arrays to a java servlet via ajax, receive that data and go through it.

Ex:

var datos=[[1,2,3],[4,5,6],[7,8,9]];
$.ajax({
   url: servlet,
   dataType: 'json',
   type: 'post',
   data: { lista: datos },
   success:function(){}
  });

Send that by ajax to a servlet. How do I receive it and go through it in java?

    
asked by EvolutionxD 24.06.2016 в 18:22
source

1 answer

1

You are using datatype json , so jQuery will send your parameters as body of the request, not as the classic multipart/form-data so you can not receive them with getParameters , you have to read the body of the request , and that will return a json as a string, then you can pass it to some parser of json and get the data of your arrangement.

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*Error leyendo los datos, ejm. conexión interrumpida, etc. */}

  try {
    // jb.toString(); // el json como cadena
    JSONObject objetoJson =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // error formateando el json
    throw new IOException("Error convirtiendo el Json");
  }

  JSONArray arr = objetoJson.getJSONArray("lista"); // obteniendo tu lista
}
    
answered by 19.06.2017 в 00:22