Spring 引导中的 Highchart

Highchart in Spring boot

我尝试在 spring 引导中使用 hightchart 来绘制折线图。但我无法获得折线图,只能在我的视图中显示空白结果。 这是我的视角

    $.ajax({
        url:'${pageContext.request.contextPath}/hawker/linechartdata',
        dataType: 'json'
        success: function(result){
            var month = JSON.parse(result).month;
            var report = JSON.parse(result).report;
            drawLineChart(month, report);
        }
    
    })
    
    
    function drawLineChart(month,report){
    document.addEventListener('DOMContentLoaded', function () {
       var chart = Highcharts.chart('container', {
            chart: {
                type: 'line'
            },
            title: {
                text: 'Fruit Consumption'
            },
            xAxis: {
                categories: month
            },
            yAxis: {
                title: {
                    text: 'Fruit eaten'
                }
            },
            series: [{
                name: 'Jane',
                data: report
            }]
        });
    });     
    }
    
    <!--Here to show the graph -->
    <div id="container"></div>

我的控制器使用Json

    @RequestMapping("/linechartdata")
    @ResponseBody
    public String getDataFromDb(@AuthenticationPrincipal UserDetails user) {
    User currentuser = userRepository.findByUsername(user.getUsername());
    Optional<Hawker> hawker = hawkerService.getHawkerByUserId(currentuser.getId());
    //Get the report list
    List<Report> reportList = reportService.findByHawId(hawker.get().getHaw_id());

    JsonArray jsonMonth = new JsonArray();
    JsonArray jsonReport = new JsonArray();
    JsonObject json = new JsonObject();

    reportList.forEach(report->{
        jsonMonth.add(report.getMonth()+1);
        jsonReport.add(report.getTotal_sales());
    });
    json.add("month", jsonMonth);
    json.add("report", jsonReport);

    return json.toString();

当我删除 ajax 并添加手动数据时,它会显示图表。请帮助我,谢谢。

您无需在控制器代码中手动创建 json,spring 引导会为您处理。您应该以 javascript.

所期望的形式创建一个 dto class

你的情况是:

public class LineChartDto {
  private List<Integer> month; // you better call this "months" or "monthList"
  private List<BigDeciamal> report; // why do you call this "report" while this is actually "sales" 

  // all args constructor, getters
}

你的控制器方法是:

@RequestMapping("/linechartdata")
@ResponseBody // or use @RestController
public LineChartDto getSalesLineChartData(..) {
  List<Report> reportList = ..

  List<Integer> months = reportList.stream()
      .map(report -> report.getMonth()+1)
      .collect(Collectors.toList());

  List<BigDecimal> sales = reportList.stream()
      .map(Report::getTotal_sales) // better name this getTotalSales
      .collect(Collectors.toList());

  return new LineChartDto(months, sales);
}

响应将导致 json 对象:

{
  "month": [1, 2, ... ],
  "report": [100, 200, ... ]
}

至于为什么 ajax 不起作用 - 这个问题太宽泛了。从 Chrome Dev Tools Network 开始检查正在发生的网络通信,检查浏览器控制台是否有错误,添加一些 console.log() 或更好地调试您的 js。

这一行 document.addEventListener('DOMContentLoaded', function () 在我看来很可疑。我认为您不需要在每次调用图表时都添加 EventListener。 也许你应该这样做:

function drawLineChart(month,report){
    Highcharts.chart('container', {
    ...