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