gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:42:28 24 4
gpt4 key购买 nike

伙计们,我是新来的,所以请帮助我..我试图通过在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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com