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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM