我试图通过post方法从jsp文件向servlet发送一些查询,然后从servlet向jsp文件获取一些修改后的结果。
我能够成功完成第一部分,但是我无法在jsp文件中收到响应。
Servlet的发布方法是:-
1 2 3 4 5 6 7 8 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONObject js = <some method to get json>; System.out.println(js); //works fine response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(js.toJSONString()); } |
我的jsp代码是:
1 2 3 4 5 6 7 8 | function getData() { $.post("MyServlet", { query :"Wolf of wall street", choice :"M" }, function(response) { alert("hello" + response); }); } |
输出为:
如何获取json字符串?
您正在获取json,因为响应需要对其进行字符串化。
1 2 3 4 5 6 7 8 | function getData() { $.post("MyServlet", { query :"Wolf of wall street", choice :"M" }, function(response) { alert("hello" + JSON.stringify(response)); }); } |