【问题标题】:fetching json object by ajax in jsp在jsp中通过ajax获取json对象
【发布时间】:2016-06-22 03:15:20
【问题描述】:

伙计们,我是新人,所以请帮助我.. 我正在尝试通过在 jsp 中使用 jqyery ajax 来获取 json 数据.. 但它不起作用.. 出现未定义.. 这是我的代码 在小服务程序中

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONObject json = null;
    PrintWriter pw = response.getWriter(); 

    try {
        json = new JSONObject();
        json.put("key1", "value1");
        json.put("key2", "value2");
        json.put("key3", "value3");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    pw.print(json.toString());
    pw.close(); 
}

在jsp中

$(document).ready(function(){
    $.ajax({

        url : 'Server',
        type: 'POST',
        dataType : 'json',
        error : function(that,e) {

            console.log(e);
        },
        success : function(data) {
            alert(data.json);
        }
    });

});

【问题讨论】:

  • 解析错误是什么?
  • @bmarkham 我不知道.. 控制台显示解析错误
  • @bmarkham 你有什么建议??
  • 我会检查 json 是否真的被发送到你拥有的任何 url
  • @bmarkham 好的......请告诉我......谢谢

标签: java jquery json ajax jsp


【解决方案1】:

您不应该在您的doPost 方法中调用doGet(request, response)。它可能正在写入响应。

此外,控制台的网络选项卡中会发生什么?

【讨论】:

  • 现在“未定义”正在弹出..解决方案是什么??
【解决方案2】:

你可以使用,

 response.getWriter().write(jsonStr); 
 response.flushBuffer();

所以通过响应你会得到json 字符串本身

即:

protected void doPost(HttpServletRequest request, 
        HttpServletResponse response) throws ServletException, IOException {

JSONObject json = null;
PrintWriter pw = response.getWriter(); 

try {
    json = new JSONObject();
    json.put("key1", "value1");
    json.put("key2", "value2");
    json.put("key3", "value3");
} catch (JSONException e) {
    e.printStackTrace();
}
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json.toString());
    response.flushBuffer();  //flush the written json string 
    pw.close(); 
}

【讨论】:

  • 它打印 [object object]
  • 接收方 ajax 将转换为 JSON Object ,因此您解析对象获取值例如:成功时您可以尝试 data.key1 获取 key1 值
猜你喜欢
  • 2016-06-21
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 2012-02-11
  • 1970-01-01
  • 2017-08-16
相关资源
最近更新 更多