jqplot利用ajax传值画图表(利用jsp连接数据库)

时间:2022-09-15 10:53:58

实现从数据库中取得数据,再把数据传给画jqplot的jsp界面!jsp界面再进行画图,画出我们所需的图表!

 

有两个jsp界面,7-12.jsp用来连接数据库,并把数据传给ajaxauto.jsp,ajaxauto.jsp接收数据并画出图表!

 

7-12.jsp

  1 <%@ page language="java" pageEncoding="UTF-8"%>
  2 
  3 <%@ page language="java" %>
  4 
  5 <%@ page import="com.mysql.jdbc.Driver" %>
  6 
  7 <%@ page import="java.sql.*" %>
  8 
  9 <%@ taglib prefix="s" uri="/struts-tags"%>
 10 
 11 <%
 12 
 13 //驱动程序名
 14 
 15 String driverName="com.mysql.jdbc.Driver";
 16 
 17 //数据库用户名
 18 
 19 String userName="root";
 20 
 21 //密码
 22 
 23 String userPasswd="root";
 24 
 25 //数据库名
 26 
 27 String dbName="login";
 28 
 29 //表名
 30 
 31 String tableName="meter_param_data";
 32 
 33 //联结字符串
 34 
 35 String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;
 36 
 37 Class.forName("com.mysql.jdbc.Driver").newInstance();
 38 
 39 Connection connection=DriverManager.getConnection(url);
 40 
 41 Statement statement = connection.createStatement();
 42 
 43 //String sql="SELECT * FROM "+tableName;
 44 String sqlcount ="select COUNT(*) from Meter_param_Data where Meter_param_Id =1";    
 45 ResultSet rs = statement.executeQuery(sqlcount); 
 46 //设置查询的初始与结束行数
 47 rs.next();
 48 int MpDIbegin=rs.getInt("COUNT(*)")-7;
 49 int MpDIend=rs.getInt("COUNT(*)");
 50 
 51 String sql = "select * from Meter_param_Data where Meter_param_Data_Id between "+MpDIbegin+" and "+MpDIend+"";
 52 rs = statement.executeQuery(sql); 
 53 
 54 //获得数据结果集合
 55 
 56 ResultSetMetaData rmeta = rs.getMetaData();
 57 
 58 //确定数据集的列数,亦字段数
 59 
 60 int numColumns=rmeta.getColumnCount();
 61 String dataYear = "[[";
 62 //String dataYear ="";
 63 //[['1/1/2008', 42], ['2/14/2008', 56], ['3/7/2008', 39], ['4/22/2008', 81]];
 64 // 输出每一个数据值
 65 while (rs.next()) {
 66         //获取时间
 67         String s=rs.getString("time");
 68         //对时间进行以空格分成数组
 69         String ss[]=s.split(" ");
 70         //        out.print(ss[0]);
 71         //对获取的时间行进以-分成数组
 72         String mdy[]=ss[0].split("-");
 73         //对月进行判断,如果是以0开头则取第二个数
 74         if(mdy[1].charAt(0)=='0'){
 75             mdy[1]=String.valueOf(mdy[1].charAt(1));
 76         }
 77         //对日进行判断,如果是以0开头则取第二个数
 78         if(mdy[2].charAt(0)=='0'){
 79             mdy[2]=String.valueOf(mdy[2].charAt(1));
 80         }
 81         //输出一些资料
 82 //        out.print("mdy[1]:"+mdy[1]+" ");
 83 //        out.print("mdy[1].charAt(0):"+mdy[1].charAt(0)+" ");
 84 //        out.print("mdy[1].charAt(1):"+mdy[1].charAt(1));
 85 //        out.print("月:"+mdy[1]+" ");
 86 //        out.print("日:"+mdy[2]+" ");
 87 //        out.print("年:"+mdy[0]+" ");
 88         //对获取的数据进行封装成字符串
 89         dataYear = dataYear +"'"+ mdy[1]+"/"+mdy[2]+"/"+mdy[0]+ "', " + rs.getString("Data") + "],[";
 90 //        dataYear = dataYear +mdy[1]+"/"+mdy[2]+"/"+mdy[0]+ ","+rs.getString("Data")+",";
 91 //        out.print(rs.getString("Data")+" ");
 92 //        out.print("<BR>");
 93 }
 94 int dylength = dataYear.length();
 95 // 减去生成的String后两个字符
 96 dataYear = dataYear.substring(0, dylength - 2);
 97 //在结尾加上结束符
 98 dataYear = dataYear + "]";
 99 //输出<div class="example-plot" id="chart2"></div>
100 //输出生成的字符串
101 response.setContentType("text/xml; charset=UTF-8");
102 response.setHeader("Cache-Control","no-cache");
103 out.println("<response>"); 
104 for(int i=0;i<3;i++){
105 //out.print("str为:"+ strdiv);
106 out.print("<dataYear>"+dataYear+
107            "</dataYear>");
108 //out.print(dataYear);
109 out.println("<name>"+(int)(Math.random()*10)+
110            "型笔记本</name>");
111 out.println("<count>" +(int)(Math.random()*100)+ "</count>");
112 }
113 out.println("</response>");
114 out.close();
115 rs.close(); 
116 statement.close(); 
117 connection.close(); 
118 %>


ajaxauto.jsp

  1 <%@include file="jqplotinclude.txt"%>
  2 <%@ page language="java" pageEncoding="UTF-8"%>
  3 <%@ taglib prefix="s" uri="/struts-tags"%>
  4 <%
  5 String path = request.getContextPath();
  6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  7 %>
  8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  9 <html>
 10   <head>    
 11     <title>My JSP 'autoRefresh.jsp' starting page</title>
 12     
 13     <meta http-equiv="pragma" content="no-cache">
 14     <meta http-equiv="cache-control" content="no-cache">
 15     <meta http-equiv="expires" content="0">    
 16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 17     <meta http-equiv="description" content="This is my page">
 18     <!-- Additional plugins go here -->
 19 
 20     <script class="include" type="text/javascript" src="js/jQuery/jqPlot/plugins/jqplot.logAxisRenderer.min.js"></script>
 21     <script class="include" type="text/javascript" src="js/jQuery/jqPlot/plugins/jqplot.canvasTextRenderer.min.js"></script>
 22     <script class="include" type="text/javascript" src="js/jQuery/jqPlot/plugins/jqplot.canvasAxisLabelRenderer.min.js"></script>
 23     <script class="include" type="text/javascript" src="js/jQuery/jqPlot/plugins/jqplot.canvasAxisTickRenderer.min.js"></script>
 24     <script class="include" type="text/javascript" src="js/jQuery/jqPlot/plugins/jqplot.dateAxisRenderer.min.js"></script>
 25     <script class="include" type="text/javascript" src="js/jQuery/jqPlot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
 26     <script class="include" type="text/javascript" src="js/jQuery/jqPlot/plugins/jqplot.barRenderer.min.js"></script>
 27     <!--
 28     <link rel="stylesheet" type="text/css" href="styles.css">
 29     -->
 30 
 31   </head>
 32   <script language="javascript">
 33   function createjqplot(){   
 34       //   var line2 = <s:property value="type"/>;
 35        var line2=<%=session.getAttribute("dataYear") %>;
 36        
 37 //         var line2 =XMLHttpReq.responseXML.getElementsByTagName("dataYear")[0].firstChild.nodeValue;
 38          
 39          var plot2 = $.jqplot('chart2', [line2], {
 40            axes: {      
 41              xaxis: {
 42                renderer: $.jqplot.DateAxisRenderer,
 43                label: 'Incliment Occurrance', 
 44                labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
 45                tickRenderer: $.jqplot.CanvasAxisTickRenderer,
 46                tickOptions: {
 47                    // labelPosition: 'middle',
 48                    angle: 15
 49                }
 50              },
 51              yaxis: {
 52                label: 'Incliment Factor',
 53                labelRenderer: $.jqplot.CanvasAxisLabelRenderer
 54              }
 55            }
 56          });
 57 
 58      }
 59   
 60 var XMLHttpReq;
 61      //创建XMLHttpRequest对象       
 62     function createXMLHttpRequest() {
 63         if(window.XMLHttpRequest) { //Mozilla 浏览器
 64             XMLHttpReq = new XMLHttpRequest();
 65         }
 66         else if (window.ActiveXObject) { // IE浏览器
 67             try {
 68                 XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
 69             } catch (e) {
 70                 try {
 71                     XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
 72                 } catch (e) {}
 73             }
 74         }
 75     }
 76     //发送请求函数
 77     function sendRequest() {
 78         createXMLHttpRequest();
 79         var url = "7-12.jsp";
 80         XMLHttpReq.open("GET", url, true);
 81         XMLHttpReq.onreadystatechange = processResponse;//指定响应函数
 82         XMLHttpReq.send(null);  // 发送请求
 83         
 84         
 85     }
 86     // 处理返回信息函数
 87     function processResponse() {
 88         if (XMLHttpReq.readyState == 4) { // 判断对象状态
 89             if (XMLHttpReq.status == 200) { // 信息已经成功返回,开始处理信息
 90                 DisplayHot();
 91             //一定时间后重新加载sendRequest()方法
 92                 setTimeout("sendRequest()", 3000);
 93             } else { //页面不正常
 94                 window.alert("您所请求的页面有异常。");
 95             }
 96         }
 97     }
 98     function DisplayHot() {
 99         var name = XMLHttpReq.responseXML.getElementsByTagName("name")[0].firstChild.nodeValue;
100         var count = XMLHttpReq.responseXML.getElementsByTagName("count")[0].firstChild.nodeValue;
101         document.getElementById("product").innerHTML = name;    
102         document.getElementById("count").innerHTML = count;    
103         var dataYear = XMLHttpReq.responseXML.getElementsByTagName("dataYear")[0].firstChild.nodeValue;
104     //    document.getElementById("data").innerHTML =dataYear;
105 //alert(<%=session.getAttribute("dataYear") %>);        
106 //alert(dataYear);
107         var data =eval(dataYear);
108 //alert(data);
109         var line2 =data;
110 // alert(line2);
111 
112 //         var line2 =XMLHttpReq.responseXML.getElementsByTagName("dataYear")[0].firstChild.nodeValue;
113         document.getElementById("chart2").innerHTML = "";
114          var plot2 = $.jqplot('chart2', [line2], {
115            axes: {      
116              xaxis: {
117                renderer: $.jqplot.DateAxisRenderer,
118                label: 'Incliment Occurrance', 
119                labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
120                tickRenderer: $.jqplot.CanvasAxisTickRenderer,
121                tickOptions: {
122                    // labelPosition: 'middle',
123                    angle: 15
124                }
125              },
126              yaxis: {
127                label: 'Incliment Factor',
128                labelRenderer: $.jqplot.CanvasAxisLabelRenderer
129              }
130            }
131          });
132          
133     }
134 </script>
135 <body onload =sendRequest()>
136 
137 
138 <table style="BORDER-COLLAPSE: collapse" borderColor=#111111 cellSpacing=0 cellPadding=0 width=200    bgColor=#f5efe7 border=0>
139 
140 <TR>
141    <TD align=middle bgColor=#dbc2b0 height=19 colspan="2"><B>正在热卖的笔记本</B> </TD>
142 </TR>
143 <tr>
144    <td height="20"> 型号:</td>
145    <td height="20" id="product"> </td>
146 </tr>
147 <tr>
148    <td height="20"> 销售数量:</td>
149    <td height="20" id="count"> </td>
150 </tr>
151 </table>
152 <div class="example-plot" id="chart2"></div>
153 <input type="button" value="画图" onclick="createjqplot()"/>
154 </body> 
155 </html>

 一开始是使用

<%=session.setAttribute("dataYear",dataYear) %>
<%=session.getAttribute("dataYear") %>

来传与接收数据的!但这种办法只能接收第一次传过来的数据!就是数据库有新的数据了,图表虽然有刷新,但并不能刷出新的数据!后来不用这个了!

在使用新的办法传与接收时出现了数据值属性不合理的问题!弄了我好久,也有记录下来,为:http://www.cnblogs.com/CccccYj/p/3279394.html