如何使用Ajax调用将JSON数据填充到图表中?

时间:2019-09-20 10:39:13

标签: json ajax spring-mvc

我想将json数据传递到jsp并填充到图表数据中。我怎样才能做到这一点? 以前,我通过使用model属性发送每个值来设置数据值。 在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);
            }
        });

1 个答案:

答案 0 :(得分:0)

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

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

请注意public struct TClimateData { public double tempSensor; public float tempHeater; public double humidity; } 批注。

更新您的Ajax调用以请求新路径@ResponseBody或您希望的新路径:

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); } 并将其直接返回来进一步简化。 Spring Boot将使用配置的Json库处理对Json的序列化:

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