基于jquery框架,用gvChart处理后台数据制作图形报表

首先,介绍下gvChart:
gvChart是一个利用Google Chart Tools来创建交互式图表(Charts)的jQuery插件。可创建的图表类型有Area、Line、Bar、Column和Pie五种。它使用HTML Tables做数据源来创建图表。

准备工作:引入JS

<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/jsapi.js"></script>
<script type="text/javascript" src="js/corechart.js"></script>
<script type="text/javascript" src="js/jquery.gvChart-1.0.1.min.js"></script>

对于js文件的引入这里也是需要注意的,要想实现图表的制作,这四个js文件缺一不可,且因为gvChart是基于jQuery的,所以在引入gvChart的js文件之前一定要先引入jQuery文件,若引入的先后顺序错了则制作后会无效果。

上代码

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
  <script type="text/javascript" src="js/jsapi.js"></script>
  <script type="text/javascript" src="js/corechart.js"></script>
  <script type="text/javascript" src="js/jquery.gvChart-1.0.1.min.js"></script>
  <title>图形报表</title>
 </head>
<body>
  <table id='myTable'>
   <caption>支出收入比例图</caption>
   <thead>
    <tr>
     <th></th>
     <th>一月</th>
     <th>二月</th>
     <th>三月</th>
     <th>四月</th>
     <th>五月</th>
     <th>六月</th>
     <th>七月</th>
     <th>八月</th>
     <th>九月</th>
     <th>十月</th>
     <th>十一月</th>
     <th>十二月</th>
    </tr>
   </thead>
   <tbody>
    <tr>
     <th>支出金额</th>
     <td>900</td>
     <td>600</td>
     <td>327</td>
     <td>359</td>
     <td>376</td>
     <td>398</td>
     <td>60</td>
     <td>50</td>
     <td>404</td>
     <td>700</td>
     <td>200</td>
     <td>500</td>
    </tr>
    <tr>
     <th>收入金额</th>
     <td>1167</td>
     <td>1110</td>
     <td>691</td>
     <td>165</td>
     <td>135</td>
     <td>157</td>
     <td>139</td>
     <td>136</td>
     <td>938</td>
     <td>1120</td>
     <td>55</td>
     <td>55</td>
    </tr>
    </tbody>
  </table>
</body>
<script>
  gvChartInit();
  $(document).ready(function() {
   $('#myTable').gvChart({
    chartType: 'ColumnChart', //AreaChart,LineChart,BarChart,ColumnChart,PieChart
    gvSettings: {
     vAxis: {
      title: '支出/收入金额:元'
     },
     hAxis: {
      title: '月份'
     },
     width: 900,
     height: 500,
    }
   });
  });
  </script>
</html>

效果:
在这里插入图片描述
在讲述处理后台的数据实例之前先给大家讲下gvChart在静态HTML页面的实现。
gvChart它本就是一个jQuery插件,实质就是将一个静态表格美化成为一个优美的图表,所以只要页面中的表格有数据,再通过表格的id调用gvChart的方法,即 $(’#myTable’).gvChart({ }); 就可以将一个普通的表格变为一个优美的图表了。
需要注意的点:

  • 在调用gvChart({})方法之前要先调用实现 gvChartInit()方法,否则将会不成功。
  • 表格table中的caption、thead、tbody、th等标签一定要写,不可省略,且第一个tr中要在前面留一个空的th单元格(总之按照上面的格式来,别想着偷懒或改动标签(内容除外))
  • 对于gvChart的chartType属性,它共有五个值:
    • AreaChart //折线图(有面积)
    • LineChart //折线图
    • BarChart //横向柱状图
    • ColumnChart //柱状图
    • PieChart //饼状图

实例应用

实训期间,在做一个房屋出租管理系统时,有个功能需要给用户直观的显示支出金额的分析图。

前台jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>无标题文档</title>
  <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
  <script type="text/javascript" src="${pageContext.request.contextPath}/layer/layer.js"></script>
  <script type="text/javascript" src="${pageContext.request.contextPath }/js/base.js"></script>
  <script type="text/javascript" src="${pageContext.request.contextPath}/js/zhichu/myzhichu.js"></script>
  <!-- 比例图的js文件 -->
  <script type="text/javascript" src="${pageContext.request.contextPath }/js/jsapi.js"></script>
  <script type="text/javascript" src="${pageContext.request.contextPath }/js/corechart.js"></script>
  <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.gvChart-1.0.1.min.js"></script>
  <SCRIPT type="text/javascript">
  
  var $webName="${pageContext.request.contextPath}";
  
</SCRIPT>
 </head>
 <body>
 
    <img alt="" src="" id="x" style="display: none;">
 
  <!-- 位置信息 -->
  <div class="place">
   <span>位置:</span>
   <ul class="placeul">
    <li>首页</li>
    <li>现金支出管理</li>
    <li>现金支出内容</li>
   </ul>
  </div>
  <!-- 内容表格信息 -->
  <div class="rightinfo">
   <div class="tools">
    <ul class="toolbar">
     <li class="addPart">
      <span><img src="${pageContext.request.contextPath }/images/t01.png" /> </span>添加
     </li>
    </ul>
    <ul class="toolbar">
     <li class="seAll">
      <span><img src="${pageContext.request.contextPath }/images/t01.png" /> </span>支出分析图
     </li>
    </ul>
    
   </div>
   <!-- 数据显示 -->
   <table class="tablelist"></table>
   <%-- 分页位置 --%>
   <div class="pagin">
    <div class="message"></div>
   </div>
  </div>
  
  <!-- 支出分析图位置 -->
  <table id='myTable5'></table>
  
 </body>
</html>

js的处理:

function getSeAll() {
 $(".seAll").click(function() {
  $.ajax({ //ajax发送请求
   url : $webName + '/zhichu/getBar3D.do',
   dataType : 'json',
   type : 'post',
   data : '',
   success : function(mydata) { //处理请求成功后执行的方法
    //1、清除原有数据
    $(".place").remove();
    $(".rightinfo").empty();
    //2、动态拼接表格数据
    var caption = $("<caption>支出比例图</caption>");
    var thead = $("<thead><tr><th></th><th>常用物件</th><th>房屋维修</th><th>退还房租或押金</th><th>其它</th></tr></thead>");
    var tbody = $("<tbody><tr><th>支出金额</th><td>"+mydata.cywj+"</td><td>"+mydata.fwwx+"</td><td>"+mydata.thje+"</td><td>"+mydata.qt+"</td></tr></tbody>");
    $("#myTable5").append(caption).append(thead).append(tbody); //将元素append加入到myTable5表格中
    //3、给myTable5表格调用gvChart方法
    gvChartInit();
    $('#myTable5').gvChart({
     chartType: 'ColumnChart', //柱状图
     gvSettings: {
      vAxis: {title: '支出金额/元'},
      hAxis: {title: '支出条目'},
      width: 900,
      height: 500,
     }
    });
   }
  });
 });
}

后台controller类的处理:

/**
  * @return
  * 支出比例图
  */
 @RequestMapping("/zhichu/getBar3D.do")
 @ResponseBody
 public Map<String,Double> getBar3D() {
  //查询全部支出信息
  List<Myzhichu> list = myzhichuService.findAllzhichuZong();
  //定义四个double类型的变量
  double cywj = 0; //常用物件
  double fwwx = 0; //房屋维修
  double thje = 0; //退还房租或押金
  double qt = 0; //其它
  for (int i = 0; i < list.size(); i++) {
   if (list.get(i).getZtm().equals("常用物件")) {
    cywj += list.get(i).getZmoney();
   }else if (list.get(i).getZtm().equals("房屋维修")) {
    fwwx += list.get(i).getZmoney();
   }else if (list.get(i).getZtm().equals("退还房租或押金")) {
    thje += list.get(i).getZmoney();
   }else {
    qt += list.get(i).getZmoney();
   }
  }
  Map<String,Double> map = new HashMap<String, Double>();
  map.put("cywj", cywj);
  map.put("fwwx", fwwx);
  map.put("thje", thje);
  map.put("qt", qt);
  return map;
 }

具体的应用代码中的注释已经写清楚的了,要想实现图表效果主要是对于数据的处理,拿到自己需要显示的数据并调用gvChart方法就能实现了。

附:数据库
在这里插入图片描述
实现效果:
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
/* @license * jQuery.print, version 1.3.2 * (c) Sathvik Ponangi, Doers' Guild * Licence: CC-By (http://creativecommons.org/licenses/by/3.0/) *--------------------------------------------------------------------------*/ (function ($) { "use strict"; // A nice closure for our definitions function getjQueryObject(string) { // Make string a vaild jQuery thing var jqObj = $(""); try { jqObj = $(string) .clone(); } catch (e) { jqObj = $("<span />") .html(string); } return jqObj; } function printFrame(frameWindow) { // Print the selected window/iframe var def = $.Deferred(); try { setTimeout(function () { // Fix for IE : Allow it to render the iframe frameWindow.focus(); try { // Fix for IE11 - printng the whole page instead of the iframe content if (!frameWindow.document.execCommand('print', false, null)) { // document.execCommand returns false if it failed -http://stackoverflow.com/a/21336448/937891 frameWindow.print(); } } catch (e) { frameWindow.print(); } frameWindow.close(); def.resolve(); }, 250); } catch (err) { def.reject(err); } return def; } function printContentInNewWindow(content) { // Open a new window and print selected content var w = window.open(); w.[removed](content); w.document.close(); return printFrame(w); } function isNode(o) { /* http://stackoverflow.com/a/384380/937891 */ return !!(typeof Node === "object" ? o instanceof Node : o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string"); } $.print = $.fn.print = function () { // Print a given set of elements var options, $this, self = this; // console.log("Printing", this, arguments); if (self instanceof $) { // Get the node if it is a jQuery object self = self.get(0); } if (isNode(self)) { // If `this` is a HTML element, i.e. for // $(selector).print() $this = $(self); if (arguments.length > 0) { options = arguments[0]; } } else { if (arguments.length > 0) { // $.print(selector,options) $this = $(arguments[0]); if (isNode($this[0])) { if (arguments.length > 1) { options = arguments[1]; } } else { // $.print(options) options = arguments[0]; $this = $("html"); } } else { // $.print() $this = $("html"); } } // Default options var defaults = { globalStyles: true, mediaPrint: false, stylesheet: null, noPrintSelector: ".no-print", iframe: true, append: null, prepend: null, manuallyCopyFormValues: true, deferred: $.Deferred() }; // Merge with user-options options = $.extend({}, defaults, (options || {})); var $styles = $(""); if (options.globalStyles) { // Apply the stlyes from the current sheet to the printed page $styles = $("style, link, meta, title"); } else if (options.mediaPrint) { // Apply the media-print stylesheet $styles = $("link[media=print]"); } if (options.stylesheet) { // Add a custom stylesheet if given $styles = $.merge($styles, $('<link rel="stylesheet" href="' + options.stylesheet + '">')); } // Create a copy of the element to print var copy = $this.clone(); // Wrap it in a span to get the HTML markup string copy = $("<span/>") .append(copy); // Remove unwanted elements copy.find(options.noPrintSelector) .remove(); // Add in the styles copy.append($styles.clone()); // Appedned content copy.append(getjQueryObject(options.append)); // Prepended content copy.prepend(getjQueryObject(options.prepend)); if (options.manuallyCopyFormValues) { // Manually copy form values into the HTML for printing user-modified input fields // http://stackoverflow.com/a/26707753 copy.find("input") .each(function () { var $field = $(this); if ($field.is("[type='radio']") || $field.is("[type='checkbox']")) { if ($field.prop("checked")) { $field.attr("checked", "checked"); } } else { $field.attr("value", $field.val()); } }); copy.find("select").each(function () { var $field = $(this); $field.find(":selected").attr("selected", "selected"); }); copy.find("textarea").each(function () { // Fix for https://github.com/DoersGuild/jQuery.print/issues/18#issuecomment-96451589 var $field = $(this); $field.text($field.val()); }); } // Get the HTML markup string var content = copy.html(); // Notify with generated markup & cloned elements - useful for logging, etc try { options.deferred.notify('generated_markup', content, copy); } catch (err) { console.warn('Error notifying deferred', err); } // Destroy the copy copy.remove(); if (options.iframe) { // Use an iframe for printing try { var $iframe = $(options.iframe + ""); var iframeCount = $iframe.length; if (iframeCount === 0) { // Create a new iFrame if none is given $iframe = $('<iframe height="0" width="0" border="0" wmode="Opaque"/>') .prependTo('body') .css({ "position": "absolute", "top": -999, "left": -999 }); } var w, wdoc; w = $iframe.get(0); w = w.contentWindow || w.contentDocument || w; wdoc = w.document || w.contentDocument || w; wdoc.open(); wdoc.write(content); wdoc.close(); printFrame(w) .done(function () { // Success setTimeout(function () { // Wait for IE if (iframeCount === 0) { // Destroy the iframe if created here $iframe.remove(); } }, 100); }) .fail(function (err) { // Use the pop-up method if iframe fails for some reason console.error("Failed to print from iframe", err); printContentInNewWindow(content); }) .always(function () { try { options.deferred.resolve(); } catch (err) { console.warn('Error notifying deferred', err); } }); } catch (e) { // Use the pop-up method if iframe fails for some reason console.error("Failed to print from iframe", e.stack, e.message); printContentInNewWindow(content) .always(function () { try { options.deferred.resolve(); } catch (err) { console.warn('Error notifying deferred', err); } }); } } else { // Use a new window for printing printContentInNewWindow(content) .always(function () { try { options.deferred.resolve(); } catch (err) { console.warn('Error notifying deferred', err); } }); } return this; }; })(jQuery);
可以通过 jQuery 的 `$.ajax()` 方法来实现分批请求后台处理数据。 首先,将需要处理数据按照一定的规则分成多个批次,然后使用 `$.ajax()` 方法依次发送每个批次的数据后台处理。 例如,假设有一个数组 `data` 需要处理,每次处理10个元素,可以按照如下方式进行分批请求: ```javascript var batchSize = 10; // 每批次处理的元素个数 var dataLength = data.length; var batchCount = Math.ceil(dataLength / batchSize); // 批次数 for (var i = 0; i < batchCount; i++) { var start = i * batchSize; // 当前批次的起始索引 var end = Math.min(start + batchSize, dataLength); // 当前批次的结束索引 var batchData = data.slice(start, end); // 当前批次的数据 $.ajax({ url: 'your_backend_url', type: 'POST', data: batchData, success: function(response) { // 处理当前批次的响应数据 } }); } ``` 注意,在上述代码中,`start` 和 `end` 变量分别表示当前批次的起始索引和结束索引。`batchData` 变量表示当前批次的数据,使用 `Array.prototype.slice()` 方法从原始数据中截取。 同时,`$.ajax()` 方法需要设置 `url`、`type` 和 `data` 属性,分别表示请求的后台地址、请求类型和发送的数据。请求成功后,可以在 `success` 回调函数中处理当前批次的响应数据。 以上就是一个简单的分批请求后台处理数据的实现方式,具体实现还需要根据具体的需求进行调整。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值