Sweep json object with $ .each jquery

0

I'm making a request to my Servlet and getting the json data as per the code below:

    $(document).ready(function(){
       $.post("MesaController",function(response){
          $.each(response,function(i,v){
             $("<button>")
               .text(v.nome).appendTo($("#mesas"));
           });
    //console.log(response);
       });
    });

However, the following error is occurring:

    jquery.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search 
    for 'length' in [{"id":1,"nome":"mesa 1"},{"id":2,"nome":"mesa 2"},
    {"id":3,"nome":"mesa 3"}]
    at w (jquery.min.js:2)
    at Function.each (jquery.min.js:2)
    at Object.success (mesa.js:8)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)
    
asked by anonymous 03.11.2017 / 05:13

1 answer

1

The solution to my problem was to put the following command in the servlet:

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

    try {
        ArrayList<Mesa> lista = new MesaDAO().listar();
        String listaJson = new Gson().toJson(lista);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(listaJson);

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(MesaController.class.getName()).log(Level.SEVERE, 
    null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(MesaController.class.getName()).log(Level.SEVERE, 
    null, ex);
    }
}

reference: link

    
07.11.2017 / 16:36