A
A
Arthur Braver2016-01-20 16:17:17
JavaScript
Arthur Braver, 2016-01-20 16:17:17

How does jQuery accept a collection from Java?

Tell me, how does the code in jQuery look like, accepting a collection of type String sent from the server (servlet)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evhen, 2016-01-21
@EugeneP2

If you want to pass something to JavaScript, it is better to first translate it into json, in your case it is a collection.
There are two ways to pass data to JavaScript/JQuery:
Servlet Page

@WebServlet(urlPatterns = "/home") // javax.servlet-api 3.0
public class HomeServlet extends HttpServlet {

  private final Gson gson = new Gson();

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    List<String> users = Arrays.asList("Vaya", "Petya", "Fedya");

    String json = gson.toJson(users);
    req.setAttribute("usersJson", json);

    req.getRequestDispatcher("/home.jsp").forward(req,resp);
  }
}

Page
<html>
<head>
    <script src="js/jquery-1.9.1.js"></script>
</head>
<body>
<script>
    var users = ${usersJson};

    $.each(users, function(i, val) {
.....................
    });
</script>
</body>
</html>

Servlet
@WebServlet(urlPatterns = "/json")
public class JsonServlet extends HttpServlet {

  private final Gson gson = new Gson();


  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    List<String> users = Arrays.asList("Vaya", "Petya", "Fedya");

    resp.addHeader("Content-Type", "application/json");

    String json = gson.toJson(users);

    resp.getWriter().print(json);

    resp.flushBuffer();
  }
}

Page
<html>
<head>
    <script src="js/jquery-1.9.1.js"></script>
</head>
<body>
<script>
    $.get('json', function(data) {
        $.each(data, function(i, val) {
            ..............................
        });
    });

</script>
</body>
</html>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question