java - jsp中通过ajax获取json对象

标签 java jquery json ajax jsp

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

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);
        }
    });

});

最佳答案

你可以使用,

 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(); 
}

关于java - jsp中通过ajax获取json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35862924/

相关文章:

jquery - 在哪里存储 jQuery 的 html 代码?

javascript - Selenium 网络驱动程序 : Element is not currently visible

java - JAX-RS - 避免 REST 请求中的新字段生成 400 - 错误请求

python - 将带有json列的数据从mysql导入到elasticsearch

java - npm 与 java - 抛出错误

Jquery .load() 使用表单中的数据

java - JNA:缺少一些具体方法

java - 由于 globStatus,MapReduce 作业未产生输出

java - 为什么无法通过smtp服务器发送邮件?

java - 通过 java -jar 执行失败,而相同的代码通过 eclipse 运行良好