今天想用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);