chart.js操作实例(前后台互通)

前提:需要导入chart.js

我的项目环境是:SpringMVC+mongodb

SpringMVC的controller层:

/**
	 * 查询得到财务信息报表
	 * @author liupeng
	 * @param request
	 * @return
	 * @throws UnknownHostException
	 * @throws ParseException
	 */
	@RequestMapping(value="/innerChartOutForFinal")
	public ModelAndView  innerChartOut(HttpServletRequest request) throws UnknownHostException, ParseException{
		String timeStartemp = request.getParameter("timeStart")==null?"":request.getParameter("timeStart").toString();
		String timeEndTemp = request.getParameter("timeEnd")==null?"":request.getParameter("timeEnd").toString();

		String timeStart = getNextDate(timeStartemp, 0, Calendar.DATE, "yyyy-MM-dd");//获取当天
		String timeEnd = getNextDate(timeEndTemp, 1, Calendar.DATE, "yyyy-MM-dd");//获取后一天

		KeyRequestDao kqDao = new KeyRequestDao();
		List<KeyRequest> list = kqDao.findByTimeForFinalCommon(timeStart, timeEnd);

		SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd");
		Date tempDate =null;
		String str = null;

		//yyyy-MM-dd HH mm ss转换为yyyy-MM-dd
		for (KeyRequest keyRequest : list) {
			tempDate = s1.parse(keyRequest.getKqTimerStart());//将时间转换为Date类型
			str = s2.format(s2.parse(s1.format(tempDate)));
			keyRequest.setKqTimerStart(str);
		}

		//横坐标:时间
		StringBuffer stringBufferX = new StringBuffer();
		//纵坐标:财务应收金额和实际到账金额
		StringBuffer stringBufferY1 = new StringBuffer();
		StringBuffer stringBufferY2 = new StringBuffer();

		String tempTime = list.get(0).getKqTimerStart();
		int tempKqAutoSum = 0;
		int tempKqAccountSum = 0;

		for (int i=0;i<list.size();i++) {
			KeyRequest keyRequest = list.get(i);
			if (keyRequest.getKqTimerStart().equals(tempTime)) {
				//应到账
				tempKqAutoSum = tempKqAutoSum + Integer.parseInt(keyRequest.getKqAutoSum());
				//实际到账
				tempKqAccountSum = tempKqAccountSum + Integer.parseInt(keyRequest.getKqAccountSum()==""?"0":keyRequest.getKqAccountSum());
				if (i==list.size()-1) {
					stringBufferX.append("'"+tempTime+"'"); //必须拼凑成这种形式,在前台的JS中才能显示,这种形式的数据为'2014-08-12'
					stringBufferX.append(",");

					stringBufferY1.append(String.valueOf(tempKqAutoSum));
					stringBufferY1.append(",");

					stringBufferY2.append(String.valueOf(tempKqAccountSum));
					stringBufferY2.append(",");
				}

			}else {
				stringBufferX.append("'"+tempTime+"'");
				stringBufferX.append(",");

				stringBufferY1.append(String.valueOf(tempKqAutoSum));
				stringBufferY1.append(",");

				stringBufferY2.append(String.valueOf(tempKqAccountSum));
				stringBufferY2.append(",");

				tempTime = keyRequest.getKqTimerStart();
				tempKqAutoSum = 0;
				tempKqAccountSum = 0;
				i--;
			}
		}

		String strx = stringBufferX.toString();
		String strY1 = stringBufferY1.toString();
		String strY2 = stringBufferY2.toString();

		System.out.println(strx);
		System.out.println(strY1);
		System.out.println(strY2);

		request.setAttribute("strx", strx);
		request.setAttribute("strY1", strY1);
		request.setAttribute("strY2", strY2);
		ModelAndView mv = new ModelAndView("/innerChart");
		return mv;

		/*
		KeyRequestDao kqDao = new KeyRequestDao();
		List<DBObject> list = kqDao.findByTimeForFinal(timeStart,timeEnd);

		//横坐标:时间
		StringBuffer stringBufferX = new StringBuffer();
		//纵坐标:财务应收金额和实际到账金额
		StringBuffer stringBufferY1 = new StringBuffer();
		StringBuffer stringBufferY2 = new StringBuffer();

		for(DBObject dbObject : list){
			stringBufferX.append(dbObject.get("kq_timer_start"));
			stringBufferX.append(",");

			stringBufferY1.append(dbObject.get("kq_autosum"));
			stringBufferY2.append(dbObject.get("kq_accountsum"));
		}

		String strY1[] = stringBufferY1.toString().split("_");
		String strY2[] = stringBufferY2.toString().split("_");

		System.out.println(stringBufferX);
		System.out.println(strY1);
		System.out.println(strY2);
		*/

	}

/**
	 * 此函数实现:给定日期和经过天数,算出结果日期
		其中sDate为指定日期,iDate为多少时间段(可以是 年、月、日...  具体根据iCal来确定)
		iCal为某种时间段例如  月:Calendar.MONTH(具体可查询api中Calendar类)
		sStr为日期格式 例如:"yyyyMMdd"(具体可查询api中Calendar类)
	 * @param sDate
	 * @param iDate
	 * @param iCal
	 * @param sStr
	 * @return
	 */
	public String getNextDate(String sDate, int iDate,int iCal, String sStr){
        String sNextDate = "";
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat(sStr);
        Date date = null;
        try {
            date = formatter.parse(sDate);
        } catch (ParseException e) {
        	e.printStackTrace();
        }
        calendar.setTime(date);
        calendar.add(iCal, iDate);
        sNextDate = formatter.format(calendar.getTime());
        return sNextDate ;
    }

SpringMVC的DAO层:

/**
	 * 根据时间范围获取全部信息
	 * @author liupeng
	 * @param timeStart
	 * @param timeEnd
	 */
	public List<KeyRequest> findByTimeForFinalCommon(String timeStart, String timeEnd) {
		List<KeyRequest> kRList = new ArrayList<KeyRequest>();
		BasicDBObject obj = new BasicDBObject();
		obj.put("kq_timer_start",new BasicDBObject("$gte",timeStart).append("$lt", timeEnd));
		try{
			DBCursor dbCursor = keyRequest.find(obj).sort(new BasicDBObject("kq_timer_start",1));//以时间倒序排序,不排序的话数据会有问题,X坐标会显示相同的时间
			List<DBObject> list = dbCursor.toArray();
			for (DBObject dbObject:list) {
				KeyRequest tmp = setKeyRequest(dbObject);
				kRList.add(tmp);
			}

		}catch (Exception e) {
			e.printStackTrace();
		}
		return kRList;
	}

SpringMVC的显示层:

<%
		String strx = (String)request.getAttribute("strx");
		String strY1 = (String)request.getAttribute("strY1");
		String strY2 = (String)request.getAttribute("strY2");
		//"January","February","March","April","May","June","July"
	%>

	<script>
    var data = {
            labels : [<%=strx%>],
            datasets : [
                {
                	//曲线的填充颜色
                    fillColor : "rgba(220,220,220,0.5)",
                	//填充块的边框线的颜色
                    strokeColor : "rgba(220,220,220,1)",
                	//表示数据的圆圈的颜色
                    pointColor : "rgba(220,220,220,1)",
                	//表示数据的圆圈的边的颜色
                    pointStrokeColor : "#fff",
                    data : [<%=strY1%>]
                },
                {
                    fillColor : "rgba(151,187,205,0.5)",
                    strokeColor : "rgba(151,187,205,1)",
                    pointColor : "rgba(151,187,205,1)",
                    pointStrokeColor : "#fff",
                    data : [<%=strY2%>]
                }
            ]
        };
    var options = {
    		scaleOverride :false, //是否显示折线图的线条
    		scaleShowLabels :true,//是否显示纵轴
    		scaleShowGridLines :true,//是否显示坐标轴的标尺
    		bezierCurve :true,//是否显示圆滑的效果
    		pointDot :true,//是否显示折线图的顶点
    		pointDotRadius :3,//折线图定点大小
    		pointDotStrokeWidth:1,//折线图定点外围大小
    		animation :true,//是否显示动画效果
    		animationSteps :60,//图形显示的速度
    };

        var ctx = document.getElementById("bar").getContext("2d");
        var myNewChart = new Chart(ctx).Line(data,options);  

    </script>  

chart.js操作实例(前后台互通)

时间: 2025-01-14 05:34:45

chart.js操作实例(前后台互通)的相关文章

HTML5的自定义属性data-*详细介绍和JS操作实例

当然高级浏览器下可通过脚本进行定义和数据存取.在项目实践中非常有用. 例如: 复制代码 代码如下: <div id = "user" data-uid = "12345" data-uname = "脚本之家" > </div> 使用attribute方法存取 data-* 自定义属性的值 使用attributes方法存取 data-* 自定义属性的值非常方便: 复制代码 代码如下: // 使用getAttribute获取

js中select操作实例

window.onload=function(){ //创建select var select1= document.createElement("select"); select1.id="select1"; for(var i=0;i<5;i++){ //创建option var option=document.createElement("option"); //var option=new option(); option.valu

C#实现的JS操作类实例

本文实例讲述了C#实现的JS操作类.分享给大家供大家参考.具体如下: 这个C#类封装了常用的JS客户端代码操作,包括弹出对话框.返回上一页,通过JS转向,弹出警告框并转向等. using System.Web; namespace DotNet.Utilities { /// <summary> /// 客户端脚本输出 /// </summary> public class JsHelper { /// <summary> /// 弹出信息,并跳转指定页面. /// &

js 操作select和option

js 操作select和option 1.动态创建select function createSelect(){ var mySelect = document.createElement_x("select");          mySelect.id = "mySelect";           document.body.appendChild(mySelect);      } 2.添加选项option function addOption(){ //根

svg DOM的一些js操作

这是第一个实例,其中讲了如何新建svg,添加元素,保存svg document,查看svg. 下面将附上常用一些元素的添加方法:(为js的,但基本上跟java中操作一样,就是类名有点细微差别) Circle var svgns = "http://www.w3.org/2000/svg"; function makeShape(evt) { if ( window.svgDocument == null ) svgDocument = evt.target.ownerDocument;

chart.js使用常见问题

Chart.js是一个简单.面向对象.为设计者和开发者准备的图表绘制工具库. 在使用过程中新手可能会遇到很多问题导致图标无法显示.下面我们来看一下在使用过程中可能会遇到的问题. 刚开始用chart.js的新手可能最先使用的就是chart.js的中文文档,根据中文文档所写的操作步骤完成操作. 首先,下载chart.js文件,通常我们从github下载. 初次使用,我们通常会直接点击图片右下角的clone or download直接下载zip文件,然后在解压后的文件中找到chart.js文件,之后引

Chart.js演示7种不同的统计图

超酷HTML5 Canvas图表应用Chart.js自定义提示折线 实例代码下载 Java代码   <div class="htmleaf-container"> <div class="htmleaf-content"> <div style="width:30%;margin:0 auto;"> <div> <canvas id="canvas" height=&quo

ajax跨域请求操作实例

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS</title> <style> #box{ width:600px; height:200px; padding:20px; border:1px solid #999; } </style> </head> <

Chart.js: 一个简单的 JS Chart Library

Chart.js 是一个 Open Source 的 JavaScript Chart Library.它一共有 6 中 Chart,全都是 HTML5 based. 底下是 Chart.js 所提供的 6 中 Charts的实例图形,包括了折线图.柱形图.圆饼图等,这样很容易在html网页中实现动态图的效果: Line Chart Bar Chart Radar Chart Pie Chart Polar Area Chart Doughnut Chart 快速上手 你可以到 github下载