ajax访问后台,得到一个对象,我怎么以json格式返回到前台
1个回答
2017-03-14 · 知道合伙人互联网行家
关注
展开全部
public class JsonServlet extends HttpServlet {
private org.codehaus.jackson.map.ObjectMapper objectMapper = new org.codehaus.jackson.map.ObjectMapper();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/json");
try {
User user = new User();
user.setId("1");
user.setName("user");
objectMapper.writeValue(resp.getOutputStream(), user);
} catch (Exception e) {
// TODO: handle exception
}
}
private static class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
前台用jquery
$.post("", {}, function(user) {
alert(user.id, +" " + user.name);
}, "json");
private org.codehaus.jackson.map.ObjectMapper objectMapper = new org.codehaus.jackson.map.ObjectMapper();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/json");
try {
User user = new User();
user.setId("1");
user.setName("user");
objectMapper.writeValue(resp.getOutputStream(), user);
} catch (Exception e) {
// TODO: handle exception
}
}
private static class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
前台用jquery
$.post("", {}, function(user) {
alert(user.id, +" " + user.name);
}, "json");
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询