zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    VisualStudioAddIn2017.vsix的下载安装和使用
    数独计算程序的比较
    Ajax
    VSTO作品:OutlookMailViewer的下载和使用
    VB6实现Excel多工作簿数据合并
    组件中 data 为什么是一个函数?
    谈谈你对 keep-alive 的了解?
    父组件可以监听到子组件的生命周期吗?
    Vue 的父组件和子组件生命周期钩子函数执行顺序?
    谈谈你对 Vue 生命周期的理解?
  • 原文地址:https://www.cnblogs.com/royi123/p/5255552.html
Copyright © 2011-2022 走看看