从后端向前端传递数据到ajax
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.创建Java工程
js 插件引入
highcharts.js
jquery-1.8.3.min.js
myjs.js 引入ajax
2.前端代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
$(function () {
var jsonstr = '';
var xmlHttp = getXmlHttpRequest();
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
{
jsonstr = eval("("+xmlHttp.responseText+")");
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: '游戏人物状态'
},
xAxis: {
categories: ['血量', '攻击', '防御'] //指定x轴分组
},
yAxis: {
title: {
text: 'something'
}
},
series:jsonstr
/* [{ //指定数据列
name: '奥特曼', //数据列名
data: [400, 32, 40] //数据
}, {
name: '怪兽boss',
data: [1000, 17, 25]
}] */
});
}
}
};
xmlHttp.open("get", "dataConverterServlet",true);
xmlHttp.send();
});
3.后端代码:
public class DataConverterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String jString ="["
+ "{name: '奥特曼',data: [800, 32, 40]},"
+ "{name: '怪兽boss',data: [1000, 27, 25]}"
+ "]";
out.print(jString);//将文本传递到前端ajax
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}