Spring MVC 中Ajax返回字符串

今天想用Ajax返回一个html的字符串数据。

JavaScript代码:

 1 function saveMarkSolve() {
 2     //editor1.sync();
 3     //var s = editor1.html();
 4     $.ajax({
 5            type: "GET",
 6            dataType: "html",
 7            url: "../exceptions/getHtml",
 8            //data: "ExceptionId=" + exceptionId,
 9            success: function(msg){
10                    $("#main_container").empty();
11                 $("#main_container").html(msg);
12            },error :function() {
13                alert("请求失败"); 
14            }
15         });
16     
17 }

Java代码:

  

 1 @RequestMapping(value = "/getHtml", method = RequestMethod.GET)
 2     public void getHtml(HttpServletResponse responses){
 3         try{
 4           DefaultHttpClient httpclient = new DefaultHttpClient();
 5           String uri = "http://192.168.0.6:9011/home/WWW";
 6           HttpGet httppost = new HttpGet(uri);
 7           //添加http头信息
 8           httppost.addHeader("iv-user", "liu_jun"); //认证token
 9           //http post的json数据格式:  {"name": "your name","parentId": "id_of_parent"}
10           //JSONObject obj = new JSONObject();
11          // httppost.setEntity(new StringEntity(obj.toString()));
12           HttpResponse response;
13           response = httpclient.execute(httppost);
14           //检验状态码,如果成功接收数据
15           int code = response.getStatusLine().getStatusCode();
16           Map<String, Object> msg = new HashMap<String, Object>();
17           if (code == 200) {
18               String rev = EntityUtils.toString(response.getEntity());//返回json格式: {"id": "27JpL~j4vsL0LX00E00005","version": "abc"}
19               System.out.println(rev);
20               responses.setContentType("text/html;charset=utf-8"); 
21               PrintWriter out=responses.getWriter();
22               out.print(rev);
23           } else {
24              System.out.println("111");
25           }
26       } catch (ClientProtocolException e) {
27               e.printStackTrace();
28       } catch (IOException e) {
29           e.printStackTrace();
30       } catch (Exception e) {
31               e.printStackTrace();
32       }
33     }

核心代码:

 responses.setContentType("text/html;charset=utf-8"); 
 PrintWriter out=responses.getWriter();
 out.print(rev);
原文地址:https://www.cnblogs.com/royi123/p/5255552.html