关于echarts的timeline图: ajax获取后台的map类型的jsonarray数据

fengjidly 发布于 2016/08/22 09:24
阅读 1K+
收藏 0

想要仿照官网的例子做,http://echarts.baidu.com/option.html#timeline

我在做timeline的时候,在后台写了个map,把时间轴参数作为key,value是 包括了x轴和series参数 的一个集合  ,然后传了个map的jsonobject到前台,不知道怎么在前台对应的位置获取了,求指导。比照官方例子,在例子的对应位置用ajax获取数据。


public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		RecordDAO redao = new RecordDAO();
		ArrayList<Starttime>  arr = redao.getStarttime();
		Map<String, ArrayList<Record>> map = redao.getAll(arr);
		
		JSONObject result=JSONObject.fromObject(arr);
        response.setContentType("text/html; charset=utf-8");
        System.out.println("转成json");
        System.out.println(result.toString());
        //返回给前段页面
        PrintWriter out = response.getWriter();  
        out.print(result.toString());  
        out.flush();  
        out.close();  
		 
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
		
	}



<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
     
    <title>Echarts_demo01</title>
    <script src="./js/echarts.js"></script>
    <script src="./js/esl.js"></script>
    <script src="./js/jquery-1.7.2.min.js"></script>
 
  </head>
   
  <body>
   
          <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
    <div id="main" style="height:400px;width:700px;"></div>
         
    <script type="text/javascript">
         
        // 基于准备好的dom,初始化echarts图表
        var myChart = echarts.init(document.getElementById('main'));
        myChart.showLoading({text:'正在加载数据'});
                             
        option = {
            baseOption: {
                timeline: {
                    // y: 0,
                    axisType: 'category',
                    // realtime: false,
                    // loop: false,
                    autoPlay: true,
                    // currentIndex: 2,
                    playInterval: 1000,
                    // controlStyle: {
                    //     position: 'left'
                    // },
                    data:(function(){
                             var arr=[];
                             $.ajax({
                                 type : "post",
                                 async : false, //同步执行
                                 url : "RecordServlet",
                                 data : {},
                                 dataType : "json", //返回数据形式为json
                                 success : function(result) {
                                 console.log("s");
                                     if (result) {
                                          for(var i=0;i<result.length;i++){
                                              console.log(result[i].starttime);
                                              arr.push(result[i].starttime);
                                           }    
                                        }
                                         
                                   },
                              error : function(errorMsg) {
                                  alert("图表请求数据失败!");
                                  myChart.hideLoading();
                              }
                          })
                           return arr;
                        }),
                         
                     
                    label: {
                        formatter : function(s) {
                            return (new Date(s)).getFullYear();
                        }
                    }
                },
                title: {
                    text: '每日各地市漫游次数统计'
                },
                tooltip: {},
                legend: {
                    x: 'right',
                    data: ['漫游次数'],
                     
                },
                calculable : true,
                grid: {
                    top: 80,
                    bottom: 100
                },
                xAxis: [
                    {
                        type:'category',
                        axisLabel:{'interval':0},
                        data:[],
                        splitLine: {show: false}
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: '次数(次)',
                        // max: 53500
                        max: 20000
                    }
                ],
                series: [
                    {name: '漫游次数',
                     type: 'bar',
                     data:[]
                    },
                ]
            },
             
        };   
                // 为echarts对象加载数据 
                myChart.setOption(option);    
                 
                getChartData();
                 
        function getChartData(){
                    var options = myChart.getOption();
                             $.ajax({
                                 type : "post",
                                 async : false, //同步执行
                                 url : "${pageContext.request.contextPath}/RecordServlet",
                                 data : {},
                                 dataType : "json", //返回数据形式为json
                                 success : function(result) {
                                     if (result) {
                                         for(var i=0;i<result.length;i++){
                                                options.xAxis[0].data = result[i].record.name;
                                                options.series[0].data = result[i].record.num;
                         
                                                myChart.hideLoading();
                                                myChart.setOption(options);
                                        }
                                        }
                                         
                                   },
                              error : function(errorMsg) {
                                  alert("请求数据失败!");
                                  myChart.hideLoading();
                              }
                          })
                        }
         
    </script>                               
                 
     
    
  </body>
</html>




加载中
0
f
fengjidly

或者哪位大神有这个图的demo可以参考啊?包括和后台交互的。

我修改后还是不行,

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		RecordDAO redao = new RecordDAO();
		ArrayList<Starttime>  arr = redao.getStarttime();
//		Map<String, ArrayList<Record>> map = redao.getAll(arr);
		ArrayList<ArrayList<Record>> list = new RecordDAO().getAll(arr);
		ArrayList<ArrayList<Cityname>> list2 = new RecordDAO().getCityname(arr);
		
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("starttime", arr);
		json.put("city_num", list);
		json.put("city_name", list2);
		
		JSONArray result=JSONArray.fromObject(json);
		
        response.setContentType("text/html; charset=utf-8");
        System.out.println("转成json");
        System.out.println(result.toString());
        //返回给前段页面
        PrintWriter out = response.getWriter();  
        out.print(result.toString());  
        out.flush();  
        out.close();  
		 
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
		
	}



<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>漫出量统计</title>
    <script src="./js/echarts.js"></script>
    <script src="./js/esl.js"></script>
    <script src="./js/jquery-1.11.1.min.js"></script>
    

  </head>
  
  <body>
  
  		<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
	<div id="main" style="height:400px;width:700px;"></div>
		
	<script type="text/javascript">
	
	// 基于准备好的dom,初始化echarts图表
	var myChart = echarts.init(document.getElementById('main'));
	//myChart.showLoading({text:'正在加载数据'});
	option = {
		    baseOption: {
		        timeline: {
		            // y: 0,
		            axisType: 'category',
		            // realtime: false,
		            // loop: false,
		            autoPlay: true,
		            // currentIndex: 2,
		            playInterval: 1000,
		            // controlStyle: {
		            //     position: 'left'
		            // },
		            symbolRotate:70,
		            data: []
		            
		        },
		        title: {
		            text: '每日各地市漫游次数统计'
		        },
		        tooltip: {},
		        legend: {
		            x: 'right',
		            data: ['漫游次数'],
		            
		        },
		        calculable : true,
		        grid: {
		            top: 80,
		            bottom: 100
		        },
		        xAxis: [
		            {
		                type:'category',
		                axisLabel:{'interval':0},
		                splitLine: {show: false},
		                data:[]
		            }
		        ],
		        yAxis: [
		            {
		                type: 'value',
		                name: '次数(次)',
		                // max: 53500
		                max: 20000
		            }
		        ],
		        series: [
		            {name: '漫游次数',
		             type: 'bar',
		            },
		        ]
		    },
		    
		    options: [
		    	
		    ]
		    
		};
$.ajax({
	type: "POST",
	url: "${pageContext.request.contextPath}/CitynameServlet",
	dataType:"json",
	async:false,  //同步
	success: function(result){
		alert("a");		
				
		//var result = eval(result);
		var result =[];
		starttime = result.starttime;
		city_name = result.city_name;
		city_num = result.city_num;
		alert(starttime.length);
		for (var n = 0; n < starttime.length; n++) {
		alert(city_num[n]);
        	option.baseOption.timeline.data.push(starttime[n]);
        	option.baseOption.timeline.xAxis.data.push(city_name[n]);
		    option.options.push({
		        series: {
		            data: city_num[n],
		        }
		    }); 
		
    	}
		
	}
});
		// 为echarts对象加载数据 
		myChart.setOption(option); 	
		/* myChart.on('timelinechanged', function(timelineIndex){
			// 设置 每个series里的xAxis里的值
			var arrIndex = parseInt(timelineIndex.currentIndex);
			if (arrIndex == 31) // 这里 31可理解为timeline节点数组的长度,此处的目的是防止 5.xAxis not found
				arrIndex = 0;
				option.options[arrIndex].xAxis.data=data[arrIndex];
				myChart.setOption(option);
		}); */ 
</script>
	
   
  </body>
</html>




0
szwx855
szwx855

把这句”myChart.setOption(option); “放到$.ajax中的complete:function(){}中去。

另外上面的var option={..}放到$.ajax中的beforeSend:function(){}中去。

0
szwx855
szwx855
原因是ajax还未执行完,你就执行了setOptioin,当然不行了。
返回顶部
顶部