Answer the question
In order to leave comments, you need to log in
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
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);
}
}
<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>
@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();
}
}
<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 questionAsk a Question
731 491 924 answers to any question