簡體   English   中英

如何從 jsp 中的 controller 獲取 json 數據?

[英]How to get json data from controller in jsp?

我想將我的 json 數據填充到 d3 圖表中。 但是如何從 controller 中獲取 json 數據? 這里 rootVO 是 json 文件,我正在傳遞給 jsp 但我不知道如何收集它並在 jsp 中使用它?

Controller class

@RequestMapping("/sunburst")
public String sunburstChart(Model model)
{
    model.addAttribute("jsonData", rootVO);
    return "sunburstChart";
}

我正在調用該方法的另一個 jsp 文件

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

這是我想要 json 數據的 sunburstChart.jspin

<!DOCTYPE html>
<head>
    <title>Sunburst Tutorial (d3 v4), Part 3</title>
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<style>
@import url('https://fonts.googleapis.com/css?family=Raleway');

body {
  font-family: "Raleway", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
</style>
<body>
    <svg></svg>
    <label><input class="sizeSelect" type="radio" name="mode" value="size" checked /> Size</label>
    <label><input class="sizeSelect"  type="radio" name="mode" value="count" /> Count</label>
</body>

<script>

    // Variables
    var width = 500;
    var height = 500;
    var radius = Math.min(width, height) / 2;
    var color = d3.scaleOrdinal(d3.schemeCategory20b);
    var sizeIndicator = "size";
    var colorIndicator = "sentiment";

    // Size our <svg> element, add a <g> element, and move translate 0,0 to the center of the element.
    var g = d3.select('svg')
        .attr('width', width)
        .attr('height', height)
        .append('g')
        .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');


    // Create our sunburst data structure and size it.
    var partition = d3.partition()
        .size([2 * Math.PI, radius]);


    // Get the data from our JSON file
    d3.json(
         $.ajax
        ({
            type:"GET",
            dataType : 'json',
            url : '/sunburst',
            success : function(response) 
            {

            },
            error: function() {
                alert("asda");
            }
        });
        , function(error, nodeData) {
        if (error) throw error;


        // Find the root node, calculate the node.value, and sort our nodes by node.value
        var root = d3.hierarchy(nodeData)
            .sum(function (d) { return d.size; })
            .sort(function(a, b) { return b.value - a.value; });


        // Calculate the size of each arc; save the initial angles for tweening.
        partition(root);
        arc = d3.arc()
            .startAngle(function (d) { d.x0s = d.x0; return d.x0; })
            .endAngle(function (d) { d.x1s = d.x1; return d.x1; })
            .innerRadius(function (d) { return d.y0; })
            .outerRadius(function (d) { return d.y1; });


        // Add a <g> element for each node; create the slice variable since we'll refer to this selection many times
        var slice = g.selectAll('g')
            .data(root.descendants())
            .enter().append('g').attr("class", "node");


        // Append <path> elements and draw lines based on the arc calculations. Last, color the lines and the slices.
        slice.append('path').attr("display", function (d) { return d.depth ? null : "none"; })
            .attr("d", arc)
            .style('stroke', '#fff')
            .style("fill", function (d) { return color((d.children ? d : d.parent).data.name); });


        // Populate the <text> elements with our data-driven titles.
        slice.append("text")
            .attr("transform", function(d) {
                return "translate(" + arc.centroid(d) + ")rotate(" + computeTextRotation(d) + ")"; })
            .attr("dx", "-20")
            .attr("dy", ".5em")
            .text(function(d) { return d.parent ? d.data.name : "" });


        // Redraw the Sunburst Based on User Input
        d3.selectAll(".sizeSelect").on("click", function(d,i) {

            // Determine how to size the slices.
            if (this.value === "size") {
              root.sum(function (d) { return d.size; });
            } else {
              root.count();
            }

            partition(root);

            slice.selectAll("path").transition().duration(750).attrTween("d", arcTweenPath);
            slice.selectAll("text").transition().duration(750).attrTween("transform", arcTweenText);
        });
    });


    /**
     * When switching data: interpolate the arcs in data space.
     * @param {Node} a
     * @param {Number} i
     * @return {Number}
     */
    function arcTweenPath(a, i) {

        var oi = d3.interpolate({ x0: a.x0s, x1: a.x1s }, a);

        function tween(t) {
            var b = oi(t);
            a.x0s = b.x0;
            a.x1s = b.x1;
            return arc(b);
        }

        return tween;
    }

    /**
     * When switching data: interpolate the text centroids and rotation.
     * @param {Node} a
     * @param {Number} i
     * @return {Number}
     */
    function arcTweenText(a, i) {

        var oi = d3.interpolate({ x0: a.x0s, x1: a.x1s }, a);
        function tween(t) {
            var b = oi(t);
            return "translate(" + arc.centroid(b) + ")rotate(" + computeTextRotation(b) + ")";
        }
        return tween;
    }


    /**
     * Calculate the correct distance to rotate each label based on its location in the sunburst.
     * @param {Node} d
     * @return {Number}
     */
    function computeTextRotation(d) {
        var angle = (d.x0 + d.x1) / Math.PI * 90;

        // Avoid upside-down labels
        return (angle < 120 || angle > 270) ? angle : angle + 180;  // labels as rims
        //return (angle < 180) ? angle - 90 : angle + 90;  // labels as spokes
    }

</script>

您無法以您顯示的方式發送 json-data 並實現您想要的。 為此,您可以按照以下提到的任何人進行操作:

  1. 讀取您的 json 文件,反序列化為 POJO,然后從單獨的控制器端點發送反序列化數據。 確保您從客戶端調用您的 ajax 方法,並准備好文檔 state。
  2. 讀取您的 json 文件,反序列化為 POJO,然后像您所做的那樣使用 modelAttribute 發送,即model.addAttribute("jsonData", deseriazedData); 並通過 JS 從 controller 讀取,例如: var yourJsonData=${jsonData} ,使用JSON.parse(yourJsonData)解析為 jsonData ,然后將其用於您的圖表。

但是請確保,所有事件(例如頁面加載然后從該數據生成圖表)都以所需的順序依次發生。 PS:如果發現困難,搜索閱讀json文件和map to pojo。 如果您不確定或需要更多幫助,那么 state 您的 json 文件數據結構和您的具體問題。 我會盡力幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM