ECharts SSH+JQueryAjax+Json+JSP将数据库中数据填充到ECharts中

来源:互联网 发布:最终幻想15 amd优化 编辑:程序博客网 时间:2024/05/15 01:52

1导入包,搭建SSH框架。

导入JQuery的JS包,<script src="JS/jquery-1.7.1.js"></script>

导入ECharts的包。<script src="http://s1.bdstatic.com/r/www/cache/ecom/esl/1-6-10/esl.js"></script>

前提你的SSH已经搭好了,数据已经传递到了Struts层。


2在Action层,将数据封装成JSON对象。并通过ServletResponse对象输出

我的实际功能将实际电量数据和计划电量数据显示到ECharts图表上。将实际电量和计划电量均放到ArrayList中,然后将这两个ArrayList放到一个ArrayList中,比如叫merge。之后将merge对象封装到封装到JSONArray中,这时的JSONArray其实存的是两个一位数组,然后将这个JSONArray对象通过Servlet的response对象输出,请求这个方法的JSP会获得这个对象。

public String getAllPower() {HttpServletRequest request = ServletActionContext.getRequest();HttpServletResponse response = ServletActionContext.getResponse();try {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}List<Power> powers = powerCompareService.getAllPower();// 获取实际电量和计划电量List actualPowerList = new ArrayList();List expectedPowerList = new ArrayList();for (Power power : powers) {actualPowerList.add(power.getActualPower());expectedPowerList.add(power.getExpectedPower());}List<List> merge = new ArrayList();merge.add(actualPowerList);merge.add(expectedPowerList);JSONArray jsonArray = JSONArray.fromObject(merge);try {response.setHeader("Cache-Control", "no-cache");response.setContentType("aplication/json;charset=UTF-8");response.getWriter().print(jsonArray);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}// request.setAttribute("list_powers", powers);// return "success";return null;}
注意需要return null;因为不希望struts导航到其他的地方,而是通过JQuery Ajax来请求。

3JQueryAjax请求JSON数据

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><head><meta charset="utf-8"><title>ECharts</title><!-- 来自百度CDN --><script src="http://s1.bdstatic.com/r/www/cache/ecom/esl/1-6-10/esl.js"></script><script src="JS/jquery-1.7.1.js"></script></head><body><!-- 为ECharts准备一个具备大小(宽高)的Dom --><div id="main1" style="height:400px"></div><button type="button" id="button1">显示/隐藏</button><script type="text/javascript">$(function() {$("#button1").click(function() {$("#main1").slideToggle(999);});});var actualPower = new Array();var expectedPower = new Array();$.ajax({url : 'Power.action',type : 'GET',dataType : 'json',async : false,success : function(jsonArray) {for (x in jsonArray[0]) {actualPower[x] = jsonArray[0][x];}for (x in jsonArray[0]) {expectedPower[x] = jsonArray[1][x];}}});// 路径配置require.config({paths : {'echarts' : 'http://echarts.baidu.com/build/echarts','echarts/chart/bar' : 'http://echarts.baidu.com/build/echarts'}});// 使用require([ 'echarts', 'echarts/chart/bar' // 使用柱状图就加载bar模块,按需加载], function(ec) {// 基于准备好的dom,初始化echarts图表var myChart = ec.init(document.getElementById('main1'));var option = {title : {text : '发电量对比',subtext : '模拟测试'},tooltip : {trigger : 'axis'},legend : {data : [ '逆变器', '汇流箱', '发电单元1', '发电单元2' ]},toolbox : {show : true,feature : {mark : {show : true},dataView : {show : true,readOnly : false},magicType : {show : true,type : [ 'line', 'bar' ]},restore : {show : true},saveAsImage : {show : true}}},calculable : true,xAxis : [ {type : 'category',data : [ '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月','9月', '10月', '11月', '12月' ]} ],yAxis : [ {type : 'value'} ],series : [ {name : '逆变器',type : 'line',data : actualPower,markPoint : {data : [ {type : 'max',name : '最大值'}, {type : 'min',name : '最小值'} ]},markLine : {data : [ {type : 'average',name : '平均值'} ]}}, {name : '汇流箱',type : 'bar',data : actualPower,markPoint : {data : [ {type : 'max',name : '最大值'}, {type : 'min',name : '最小值'} ]},markLine : {data : [ {type : 'average',name : '平均值'} ]}}, {name : '发电单元1',type : 'bar',data : actualPower,markPoint : {data : [ {type : 'max',name : '最大值'}, {type : 'min',name : '最小值'} ]},markLine : {data : [ {type : 'average',name : '平均值'} ]}}, {name : '发电单元2',type : 'bar',data : expectedPower,markPoint : {data : [ {name : '年最高',value : 182.2,xAxis : 7,yAxis : 183,symbolSize : 18}, {name : '年最低',value : 2.3,xAxis : 11,yAxis : 3} ]},markLine : {data : [ {type : 'average',name : '平均值'} ]}} ]};// 为echarts对象加载数据 myChart.setOption(option);});</script></body>

$.ajax({
            url : 'Power.action',
            type : 'GET',
            dataType : 'json',
            async : false,
            success : function(jsonArray) {
                for (x in jsonArray[0]) {
                    actualPower[x] = jsonArray[0][x];
                }
                for (x in jsonArray[0]) {
                    expectedPower[x] = jsonArray[1][x];
                }
            }
        });

其中 url的参数是请求的action

        dataType数据类型选择json

        success是请求成功后的返回,jsonArray就是请求成功,上面的Action的方法通过Servlet传递过来的Json对象。二维数组jsonArray[0]直接能获取到第一个封装的ArrayList,而jsonArray[0][x]获取到ArrayList中的第x个数据。


具体参考参数如下:

url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址。

type:要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和

     delete也可以使用,但仅部分浏览器支持。

timeout:要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设

        置。

async:要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。

      如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等

      待请求完成才可以执行。

cache:要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false)。

      设置为false将不会从浏览器缓存中加载请求信息。

data: 要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格

     式。get请求中将附加在url后。防止这种自动转换,可以查看processData选项。对象必须为key/value格

     式,例如{foo1:"bar1",foo2:"bar2"}转换为&foo1=bar1&foo2=bar2。如果是数组,JQuery将自动为不同

     值对应同一个名称。例如{foo:["bar1","bar2"]}转换为&foo=bar1&foo=bar2。

dataType:要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime

         信息返回responseXML或responseText,并作为回调函数参数传递。

         可用的类型如下:

         xml:返回XML文档,可用JQuery处理。

         html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。

         script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求

                 时(不在同一个域下),所有post请求都将转为get请求。

         json:返回JSON数据。

         jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个

               “?”为正确的函数名,以执行回调函数。

         text:返回纯文本字符串。

beforeSend:要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义

           HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参

           数。

           function(XMLHttpRequest){

               this;  //调用本次ajax请求时传递的options参数

           }

complete:要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。

         参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。

         function(XMLHttpRequest, textStatus){

            this;   //调用本次ajax请求时传递的options参数

         }

success:要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。

        (1)由服务器返回,并根据dataType参数进行处理后的数据。

        (2)描述状态的字符串。

        function(data, textStatus){

            //data可能是xmlDoc、jsonObj、html、text等等

           this;  //调用本次ajax请求时传递的options参数

error:要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错

      误信息、捕获的错误对象(可选)。

      ajax事件函数如下:

      function(XMLHttpRequest, textStatus, errorThrown){

         //通常情况下textStatus和errorThrown只有其中一个包含信息

         this;  //调用本次ajax请求时传递的options参数

      }

contentType:要求为String类型的参数,当发送信息至服务器时,内容编码类型默认

            为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。

dataFilter:要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。

           提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的

           dataType参数。函数返回的值将由jQuery进一步处理。

           function(data, type){

               //返回处理后的数据

               return data;

           }

global:要求为Boolean类型的参数,默认为true。表示是否触发全局ajax事件。设置为false将不会触发全局

       ajax事件,ajaxStart或ajaxStop可用于控制各种ajax事件。

ifModified:要求为Boolean类型的参数,默认为false。仅在服务器数据改变时获取新数据。

           服务器数据改变判断的依据是Last-Modified头信息。默认值是false,即忽略头信息。

jsonp:要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。

      该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,例如

      {jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。

username:要求为String类型的参数,用于响应HTTP访问认证请求的用户名。

password:要求为String类型的参数,用于响应HTTP访问认证请求的密码。

processData:要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度

            来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM

            树信息或者其他不希望转换的信息,请设置为false。

scriptCharset:要求为String类型的参数,只有当请求时dataType为"jsonp"或者"script",并且type是GET时

              才会用于强制修改字符集(charset)。通常在本地和远程的内容编码不同时使用。


4 ECharts

ECharts中的图表数据填充就是Array()对象。

data:actualPower,

这里直接填充了JSON传递过来的数据。


5显示效果图



1 0
原创粉丝点击