如何在这里摆脱硬编码值?

时间:2019-09-25 13:09:50

标签: java ajax spring

我想将数据填充到饼图中。我正在使用ArrayList传递数据。对于每条记录,我都给出了硬编码的值。如果我正在使用foreach循环,那么只有一个数据在为另一个数据进行迭代,将无法正常工作。该怎么做?

这是我的Controller方法

@RequestMapping("/pie")
public String pieChart(Model model)
{
    Map<Integer, Integer> map = getAgeKeyValue();
    Set<Map.Entry<Integer, Integer>> hmap = map.entrySet();
    ArrayList<Integer> key = new ArrayList<>();
    ArrayList<Integer> value = new ArrayList<>();
    for (Map.Entry<Integer, Integer> data : hmap)
    {
        key.add(data.getKey());
        value.add(data.getValue());
    }
    model.addAttribute("key", key);
    model.addAttribute("value", value);
    return "pieChart";
}

这是我的pieChart.jsp

<script>
$(function()
{ 
    var pieChart = new CanvasJS.Chart("pieChartContainer", 
    {
        animationEnabled: true,
        theme: "light2",
        title:
        {
            text: "Age wise total number of Employees",
            fontSize: 20,
            fontFamily: "Trebuchet MS",
            fontWeight: "bold",
            margin: 10
        },
        data: 
        [{        
            type: "pie",
            dataPoints: 
            [   
                { y: ${value[0]},  label: "${key[0]}" },                 
                { y: ${value[1]},  label: "${key[1]}" },                        
                { y: ${value[2]},  label: "${key[2]}" },
                { y: ${value[3]},  label: "${key[3]}" },
                { y: ${value[4]},  label: "${key[4]}" },
                { y: ${value[5]},  label: "${key[5]}" },
                { y: ${value[6]},  label: "${key[6]}" },
                { y: ${value[7]},  label: "${key[7]}" }

            ]
        }]
    });
    pieChart.render();
});
</script>
<div class="card shadow p-3 bg-white rounded">
    <div class="card-body">
        <div id="pieChartContainer" style="height: 240px; width: 100%;"></div>
    </div>
</div>

从另一个jsp中,我正在使用ajax调用pieChart.jsp

在这里

<div class="col-md-6 p-1">
    <div id="pieGraph"></div>
</div>

$.ajax
({
    url: "pie", 
    async: false, 
    success: function(data) 
    { 
        console.log(data); 
        $("#pieGraph").append(data);
    }
});

0 个答案:

没有答案