【问题标题】:How to receive and parse a json data from jsp?如何从jsp接收和解析json数据?
【发布时间】:2017-02-19 02:07:12
【问题描述】:

我像这样从 servlet 发送一个 json

User profileUser = userService.get(id);
request.setAttribute("profileUser", profileUser);
JSONObject json = new JSONObject();
try {
    json.put("profileUser", profileUser);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
response.setContentType("application/json");
response.getWriter().write(json.toString());

在 ajax 调用中的 javascript

$.ajax({
    cache : false,
    type : "GET",
    url : "UserServlet?id=" + userId,
    success : function(result) {
        alert(result.profileUser);
    }
});

警报的结果是给我 Entity.user 但如果我想调用 result.profileUser.uuid 或该用户的属性返回我 undefined 。谁能帮帮我?

【问题讨论】:

  • 实际的 HTTP 响应是什么?
  • @SLaks 302 临时移动

标签: java json ajax jsp servlets


【解决方案1】:

如果您将 json 发送到您的 Ajax 客户端,那么您需要指定您将要接收 json 类型。像这样:

$.ajax({
    cache : false,
    type : "GET",
    dataType : "json",
    url : "UserServlet?id=" + userId,
    success : function(result) {
        alert(result.profileUser);
    }
});

这将导致您的成功方法将结果参数评估为 json 对象。

【讨论】:

    【解决方案2】:

    将您的 Ajax 更改为以下内容:

    $.ajax({
        cache : false,
        type : "GET",
        url : "UserServlet?id=" + userId,
        success : function(profileUser) {
            alert(profileUser.uuid);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-09-05
      • 2020-03-02
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多