您的位置:首页 > 编程语言 > Java开发

Spring MVC 中Ajax返回字符串

2016-03-08 20:47 381 查看
今天想用Ajax返回一个html的字符串数据。

JavaScript代码:

function saveMarkSolve() {
//editor1.sync();
//var s = editor1.html();
$.ajax({
type: "GET",
dataType: "html",
url: "../exceptions/getHtml",
//data: "ExceptionId=" + exceptionId,
success: function(msg){
$("#main_container").empty();
$("#main_container").html(msg);
},error :function() {
alert("请求失败");
}
});

}


Java代码:

  

@RequestMapping(value = "/getHtml", method = RequestMethod.GET)
public void getHtml(HttpServletResponse responses){
try{
DefaultHttpClient httpclient = new DefaultHttpClient();
String uri = "http://192.168.0.6:9011/home/WWW";
HttpGet httppost = new HttpGet(uri);
//添加http头信息
httppost.addHeader("iv-user", "liu_jun"); //认证token
//http post的json数据格式:  {"name": "your name","parentId": "id_of_parent"}
//JSONObject obj = new JSONObject();
// httppost.setEntity(new StringEntity(obj.toString()));
HttpResponse response;
response = httpclient.execute(httppost);
//检验状态码,如果成功接收数据
int code = response.getStatusLine().getStatusCode();
Map<String, Object> msg = new HashMap<String, Object>();
if (code == 200) {
String rev = EntityUtils.toString(response.getEntity());//返回json格式: {"id": "27JpL~j4vsL0LX00E00005","version": "abc"}
System.out.println(rev);
responses.setContentType("text/html;charset=utf-8");
PrintWriter out=responses.getWriter();
out.print(rev);
} else {
System.out.println("111");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}


核心代码:

responses.setContentType("text/html;charset=utf-8");
PrintWriter out=responses.getWriter();
out.print(rev);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: