首页 > 解决方案 > 如何使用 ajax 调用将 json 数据填充到图表中?

问题描述

我想将 json 数据传递给 jsp 并填充到图表数据中。我怎样才能做到这一点?以前我通过使用模型属性发送每个值来设置数据值。在 EmployeeController 我有这样的 lineBarChart 方法: -

@RequestMapping("/lineBar")
    public String lineBarChart(Model model)
    {
        List<Employee> emp = employeeMapper.getAllEmployees();
        int cseCount = 0;
        int ecCount = 0;
        int itCount = 0;
        int cseSalary = 0;
        int ecSalary = 0;
        int itSalary = 0;

        for (int j = 0; j < emp.size(); j++)
        {
            if (emp.get(j).getDepartment().equalsIgnoreCase("CSE"))
            {
                cseSalary += emp.get(j).getSalary();
                cseCount++;
            }
            else if (emp.get(j).getDepartment().equalsIgnoreCase("IT"))
            {
                itSalary += emp.get(j).getSalary();
                itCount++;
            }
            else
            {
                ecSalary += emp.get(j).getSalary();
                ecCount++;
            }
        }

        Map<Integer, Integer> map = new HashMap<>();
        map.put(cseCount, cseSalary);
        map.put(ecCount, ecSalary);
        map.put(itCount, itSalary);

        GsonBuilder gsonMapBuilder = new GsonBuilder();
        Gson gsonObject = gsonMapBuilder.create();
        String jsonObject = gsonObject.toJson(map);
        System.out.println(jsonObject);

        // Previously i am doing this now i want to send json to chart
        model.addAttribute("cse", cseCount);
        model.addAttribute("ec", ecCount);
        model.addAttribute("it", itCount);
        model.addAttribute("cseSalary", cseSalary);
        model.addAttribute("itSalary", itSalary);
        model.addAttribute("ecSalary", ecSalary);

        return "lineBarChart";
    }

这是 lineBarChart.jsp:-

<script>
$(function()
{ 
    var lineBarChart = new CanvasJS.Chart("lineBarChartContainer", 
    {
        animationEnabled: true,
        theme: "light2",
        title:
        {
            text: "Branch wise total Employee Salary",
            fontSize: 20,
            fontFamily: "Trebuchet MS",
            fontWeight: "bold",
            margin: 10
        },
        axisY: 
        {
            title: "Number of Employee",
            suffix: " K"
        },
        data: 
        [{        
            type: "column",
            dataPoints: 
            [      
                { y: ${cse}, label: "CSE" },   
                { y: ${ec},  label: "EC" },
                { y: ${it},  label: "IT" }
            ]
        },
        {        
            type: "line",
            toolTipContent: "{label}: {y}K",        
            showInLegend: true,
            dataPoints: 
            [      
                { y: ${cseSalary}/10000, label: "CSE" },                   
                { y: ${ecSalary}/10000,  label: "EC" },                         
                { y: ${itSalary}/10000,  label: "IT" }                         
            ]
        }]
    });
    lineBarChart.render();
});
</script>
<div class="card shadow p-3 bg-white rounded">
    <div class="card-body">
        <div id="lineBarChartContainer" style="height: 240px; width: 100%;"></div>
    </div>
</div>

我正在使用 ajax 调用从另一个 jsp 调用 lineBarChart.jsp 文件。

像这样 :-

<div class="row" >
        <div class="col-md-6 p-1">
        <div id="lineBarGraph"></div>
    </div>
</div>
$.ajax({url: "lineBar",
            async: false, 
            success: function(result) 
            { 
                console.log(result);
                $("#lineBarGraph").html(result);
            }
        });

标签: jsonajaxspring-mvc

解决方案


您将需要创建第二个处理程序方法或控制器。

现有控制器将简单地加载 JSP,因此可以从中删除所有逻辑。新的控制器方法将具有加载和返回 Ajax 调用请求的数据的逻辑,如下所示。

注意@ResponseBody注释。

更新您的 Ajax 调用以请求新路径fetchChartData或任何您想要的路径:

@RequestMapping("/fetchChartData", produces="application/json")
public @ResponseBody String getChartData()
{
    List<Employee> emp = employeeMapper.getAllEmployees();
    int cseCount = 0;
    int ecCount = 0;
    int itCount = 0;
    int cseSalary = 0;
    int ecSalary = 0;
    int itSalary = 0;

    for (int j = 0; j < emp.size(); j++)
    {
        if (emp.get(j).getDepartment().equalsIgnoreCase("CSE"))
        {
            cseSalary += emp.get(j).getSalary();
            cseCount++;
        }
        else if (emp.get(j).getDepartment().equalsIgnoreCase("IT"))
        {
            itSalary += emp.get(j).getSalary();
            itCount++;
        }
        else
        {
            ecSalary += emp.get(j).getSalary();
            ecCount++;
        }
    }

    Map<Integer, Integer> map = new HashMap<>();
    map.put(cseCount, cseSalary);
    map.put(ecCount, ecSalary);
    map.put(itCount, itSalary);

    //you could remove the below and return the map directly
    GsonBuilder gsonMapBuilder = new GsonBuilder();
    Gson gsonObject = gsonMapBuilder.create();

    return gsonObject.toJson(map);
}

您可以通过将方法返回类型更改为并直接返回它来进一步简化Map<Integer, Integer>。Spring Boot 将使用配置的 Json 库处理对 Json 的序列化:

https://www.callicoder.com/configuring-spring-boot-to-use-gson-instead-of-jackson/


推荐阅读