Scan json object with $.each jquery

Asked

Viewed 186 times

0

I am making a request to my Servlet and taking the json data according to 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 occurs:

    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)
  • has tried to make JSON.stringfy from Sponse?

  • 1

    What happens if you put console.log(typeof response, JSON.stringify(response)); before the line $.each(response...?

  • When I put the command you entered Adelino string " [{"id":1,"name":"table 1"},{"id":2,"name":"table 2"}, {"id":3,"name":"table 3"}]"

1 answer

1

The solution to my problem was to put the following command on 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: https://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax

Browser other questions tagged

You are not signed in. Login or sign up in order to post.