【发布时间】:2018-04-21 16:58:19
【问题描述】:
如何从 Servlet 返回 JSON? 这是我的代码,但有些东西不起作用,我想我在 JS 代码中犯了错误,但我不知道如何更正。
这是小服务程序
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String enduser = ls.ReturnEndUser();
Utente user = ls.getUserByUsername(enduser);
String json = new Gson().toJson(user);
System.out.println("il JSON è " + json);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
JS
$.get("UserServlet", function (response) {
document.getElementById("endusername").innerHTML = utente.nome;
});
这是 Utente 对象
public Utente(String username, String nome, String cognome, String email, String password, int gruppo1, int gruppo2, int gruppo3, int gruppo4, int gruppo5,String img_src) {
this.id_utente = id_utente;
this.username = username;
this.nome = nome;
this.cognome = cognome;
this.email = email;
this.password = password;
this.gruppo1 = gruppo1;
this.gruppo2 = gruppo2;
this.gruppo3 = gruppo3;
this.gruppo4 = gruppo4;
this.gruppo5 = gruppo5;
this.img_src= img_src;
}
【问题讨论】:
标签: javascript java ajax servlets