从数据库获取数据动态加载给echarts饼图

时间:2022-10-28 11:11:28

index.ftl

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<script type="text/javascript" src="js/echarts.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<body>
    <div id="chartmain" style="width: 600px; height: 400px;"></div>
</body>
<script type="text/javascript"> //初始化echarts function chushihua(myChart){ var option = { title:{ text:'ECharts 数据统计' }, series:[{ name:'访问量', type:'pie', radius:'90%', data:[ {value:0,name:'无'}, ] }] }; myChart.setOption(option); } //从数据库读取数据赋值给echarts function fuzhi(myChart){ $.ajax({ contentType : "application/json", type : "GET", url : "info.html", dataType : "json", success : function(data) { //创建一个数组,用来装对象传给series.data,因为series.data里面不能直接鞋for循环 var servicedata=[]; for(var i=0;i<data.length;i++){ var obj=new Object(); obj.name=data[i].username; obj.value=data[i].age; servicedata[i]=obj; } myChart.setOption({ title:{ text:'ECharts 数据统计' }, series:[{ name:'访问量', type:'pie', radius:'60%', data:servicedata, }] }); } }); } //初始化echarts实例 var myChart = echarts.init(document.getElementById('chartmain')); chushihua(myChart); fuzhi(myChart); </script>
</html>

UserController

package com.lx.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lx.entity.User;
import com.lx.service.UserService;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value="/info",method=RequestMethod.GET)
    public @ResponseBody ArrayList<User> charts(HttpServletRequest request, HttpServletResponse response){

        ArrayList<User> user =userService.queryUser();
        return user;
    }

}

User.java

package com.lx.entity;

public class User {
    private int id;
    private String username;
    private int age;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

}