Practice of using Ajax to dynamically generate Echarts charts in Ruoyi

foreword

        In the previous blog post, we explained how to use java to generate Echarts chart generation components in the background. The blog post is as follows:

serial number

blog link
1 An Echarts background generation framework based on JAVA development
2 Ideas and solutions for the integration of Ruoyi single project and Echarts4.2.1 map
3 Solve the problem that the single version of Ruoyi does not display in Tab mode when integrating Echarts multi-charts

        In the previous blog, the generation of Echarts charts was introduced in a scattered way. However, when generating charts, the data source information is basically set in advance, which is equivalent to static data. For the scenario of dynamic data access, for example, it is necessary to dynamically obtain background data through ajax, and then set the data to the front-end chart component. This article will take the Ruoyi framework as an example to explain in depth the dynamic access of data based on Ajax technology, so that readers can understand how to develop dynamic data access codes in practice.

1. Maven dependency definition

        The demo project is defined in the way of Maven dependency. Here you need to introduce the Java background generation component of Echarts and the Gson package. Gson is a dependency package for generating echarts components. Please make sure to add it.

<!-- 增加Echarts java统一处理类 -->
<dependency>
	<groupId>com.github.abel533</groupId>
	<artifactId>ECharts</artifactId>
	<version>3.0.0</version>
</dependency>
		
<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.6.2</version>
</dependency>

2. Data simulation generation

        For simplicity of demonstration, only Java is used to simulate data query for data construction. In actual situations, it is necessary to query the actual data in the database. The scenario demonstrated in this example is to query the SMS sending volume information of a department in the last month.

        This is implemented in two functions. The first function is to generate the timestamp of each day in the previous month, which is convenient for display in the Echarts chart. The method is as follows. It should be noted here that the last month is obtained by using the calendar class -1:

private List<String> getEveryDayOfMonth() {
		List<String> result = new ArrayList<String>();
		//获取Calendar
		Calendar calendar=Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.add(Calendar.MONTH, -1);//获取上个月
		Date startDate = calendar.getTime();
		//设置日期为本月最大日期
		calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
		Date endDate = calendar.getTime();
		
		while(startDate.getTime() <= endDate.getTime()){
			String dayStr = DateUtils.parseDateToStr("yyyy-MM-dd", startDate);
			result.add(dayStr);
			calendar.setTime(startDate);
			calendar.add(Calendar.DATE,1);
			Date tempDate = calendar.getTime();
			startDate = tempDate;
		}
		return result;
	}

        On this basis, we simulate the information sending data every day within a month and generate Echarts objects.

public String buildOrgzSendSmsCount(String orgzName) {
		String result = "";
		List<String> dateList = this.getEveryDayOfMonth();
		
		GsonOption option = new GsonOption();
		option.title().text("【" + orgzName + "】上月短信统计(单位:条)");
        option.tooltip().trigger(Trigger.axis);
        option.legend("短信发送量");
        option.legend().y(Y.bottom).padding(0);
        option.toolbox().show(true).feature(new MagicType(Magic.line, Magic.bar).show(true), Tool.saveAsImage);
        option.calculable(true);
        
        List<String> months = new ArrayList<String>();
        List<Integer> sendCounts = new ArrayList<Integer>();
        
        Random random = new Random();
        
        for (String date : dateList) {
        	months.add(date);
        	sendCounts.add(random.nextInt(100));
		}
	        
        CategoryAxis categoreAxis = new CategoryAxis();
        categoreAxis.data(months.toArray()).axisLabel().interval(0).rotate(30);
        
        option.xAxis(categoreAxis);
        option.yAxis(new ValueAxis());

        Bar bar = new Bar("短信发送量");
        bar.data(sendCounts.toArray());
        bar.markPoint().data(new PointData().type(MarkType.max).name("最大值"), new PointData().type(MarkType.min).name("最小值"));
        bar.markLine().data(new PointData().type(MarkType.average).name("平均值"));

        option.series(bar);
        result = option.toString();
	        
		return result;
	}

3. Background interface call

        The background uses an open interface to provide external calls. For the convenience of demonstration, too many parameters are not added. The actual situation can pass relevant parameters as needed. It should be noted here that when using the AjaxResult object for output, the returned json parameters use data to carry.

@PostMapping("/echarts/getmsgsendchart")
@ResponseBody
public AjaxResult msgSendChart(){
    String charts = echartService.buildOrgzSendSmsCount("信息技术部");
    AjaxResult result = AjaxResult.success();
    result.put("data", charts);
    return result;
}

Four, Html5 web page definition

        In the html page, the following code is used to define the object of the SMS sending volume chart. The key code is as follows. Note that the height of the chart here is directly set to 200px:

<div id="tab-4" class="tab-pane">
     <div class="panel-body">
          <div class="row">
			<div class="col-sm-12">
				<div class="ibox float-e-margins">
					<div class="ibox-title">
						 <h5>短信发送量</h5>
						 <div class="ibox-tools">
						      <a class="collapse-link">
						          <i class="fa fa-chevron-up"></i>
						      </a>
						      <a class="dropdown-toggle" data-toggle="dropdown" href="#">
						          <i class="fa fa-wrench"></i>
						      </a>
						      <ul class="dropdown-menu dropdown-user">
						          <li><a href="#">选项1</a>
						          </li>
						          <li><a href="#">选项2</a>
						          </li>
						       </ul>
						       <a class="close-link">
						              <i class="fa fa-times"></i>
						       </a>
						       </div>
						       </div>
						       <div class="ibox-content">
						       <div style="height:200px" id="echarts-msgsend-chart"></div>
						      </div>
						   </div>
					</div>
				</div>
            </div>
    </div>

Five, Ajax data initialization

        Use Jquery+bootstrap to initialize the chart,

msgsendChart = echarts.init(document.getElementById("echarts-msgsend-chart"));
$(window).resize(msgsendChart.resize);
charts.push(msgsendChart);
initMsgSendChart();
function initMsgSendChart(){
	$.ajax({
		    type: "POST",
		    url: ctx + "/demo/report/echarts/getmsgsendchart",
		    data: {},
		    dataType : "json",
		    success: function(serverdata){
		    	if(serverdata != ""){
		    		var serverJsonData = eval('('+serverdata.data+')');
		    		msgsendChart.setOption(serverJsonData,true);
		    		$(window).resize(msgsendChart.resize);
		    	}
		    },
		    error:function(data){
		    		parent.layer.alert('系统发生错误!', {icon: 5});
		    	}
	    });
}

        Note that the above code is, var serverJsonData = eval('('+serverdata.data+')'); Here, the eval function is used for parameter conversion. At the same time, it should be noted that serverdata.data; the data behind is the previously mentioned The passed background returns the key in AjaxResult.

6. Chart display and process analysis

        Simulate the display effect of the histogram page of the SMS sending volume statistics. 

 Let’s take a look at the specific interface request situation:

{"msg":"操作成功","code":0,"data":"{\"calculable\": true,\"title\": {\"text\": \"【信息技术部】上月短信统计(单位:条)\"},\"toolbox\": {\"feature\": {\"magicType\": {\"show\": true,\"title\": {\"bar\": \"柱形图切换\",\"stack\": \"堆积\",\"tiled\": \"平铺\",\"line\": \"折线图切换\"},\"type\": [\"line\",\"bar\"]},\"saveAsImage\": {\"show\": true,\"title\": \"保存为图片\",\"type\": \"png\",\"lang\": [\"点击保存\"]}},\"show\": true},\"tooltip\": {\"trigger\": \"axis\"},\"legend\": {\"data\": [\"短信发送量\"],\"y\": \"bottom\",\"padding\": 0},\"xAxis\": [{\"type\": \"category\",\"axisLabel\": {\"interval\": 0,\"rotate\": 30},\"data\": [\"2023-07-01\",\"2023-07-02\",\"2023-07-03\",\"2023-07-04\",\"2023-07-05\",\"2023-07-06\",\"2023-07-07\",\"2023-07-08\",\"2023-07-09\",\"2023-07-10\",\"2023-07-11\",\"2023-07-12\",\"2023-07-13\",\"2023-07-14\",\"2023-07-15\",\"2023-07-16\",\"2023-07-17\",\"2023-07-18\",\"2023-07-19\",\"2023-07-20\",\"2023-07-21\",\"2023-07-22\",\"2023-07-23\",\"2023-07-24\",\"2023-07-25\",\"2023-07-26\",\"2023-07-27\",\"2023-07-28\",\"2023-07-29\",\"2023-07-30\",\"2023-07-31\"]}],\"yAxis\": [{\"type\": \"value\"}],\"series\": [{\"name\": \"短信发送量\",\"type\": \"bar\",\"markPoint\": {\"data\": [{\"name\": \"最大值\",\"type\": \"max\"},{\"name\": \"最小值\",\"type\": \"min\"}]},\"markLine\": {\"data\": [{\"name\": \"平均值\",\"type\": \"average\"}]},\"data\": [60,87,89,81,69,65,89,45,1,29,25,27,24,79,50,23,20,8,60,72,31,61,7,10,57,5,65,74,64,29,4]}]}"}

Summarize

        The above is the main content of this article. This article will take the Ruoyi framework as an example to explain in depth the dynamic access of data based on Ajax technology, so that readers can understand how to develop dynamic data access codes. The writing is hasty, and there are inevitably many problems. Friends are welcome to criticize and correct.

Guess you like

Origin blog.csdn.net/yelangkingwuzuhu/article/details/132113869