D3图表未呈现

My d3 chart was getting rendered before but when I included my drop downs it is giving error as Cannot read property 'forEach' of null because my json is changed now as I included values inside it..so please help where is error. Thank you.

    body {
                    color: #000;
                }

                .axis {
                  font: 10px sans-serif;
                }

                .axis path,
                .axis line {
                  fill: none;
                  stroke: #000;
                  shape-rendering: crispEdges;
                }

                .bar {
                    fill: steelblue;
                }

                .bar:hover {
                    fill: brown;
                }

            </style>

            <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
         </head>
        <script src="http://d3js.org/d3.v3.min.js"></script>
        <script
                  src="https://code.jquery.com/jquery-1.12.3.min.js"
                  integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ="
                  crossorigin="anonymous"></script>
         <script src="web.js" type="text/javascript"></script>
        <body>
            <div id="chart"></div>
            <div align ="center">
                From : <input type="date" name="field1" id="field1" />
                To :   <input type="date" name="field2" id="field2" /><br /><br />
                <input type="button" onclick="render(true)" value="Submit" />
            </div>
          <script>

                var jsonURL = './mydata.json';

                var myData = [];

                var margin  = { top: 20, right: 0, bottom: 80, left: 40 };
                var width   = 500 - margin.left - margin.right;
                var height  = 300 - margin.top - margin.bottom;

                var xScale  = d3.scale.ordinal().rangeRoundBands([0, width], .1);
                var yScale  = d3.scale.linear().range([height, 0]);
                var hAxis   = d3.svg.axis().scale(xScale).orient('bottom').tickFormat(d3.time.format("%Y-%m-%d"));
                var vAxis   = d3.svg.axis().scale(yScale).orient('left');
                var tooltip = d3.select('body').append('div')
                                .style('position', 'absolute')
                                .style('background', '#f4f4f4')
                                .style('padding', '5 15px')
                                .style('border', '1px #333 solid')
                                .style('border-radius', '5px')
                                .style('opacity', 'o');

                function getDates() {
                    return [document.getElementById('field1').value, document.getElementById('field2').value];
                }

                function render(filterByDates) {

                    d3.select('svg').remove();

                    if(filterByDates) {
                        var date1 = new Date(document.getElementById('field1').value);
                        var date2 = new Date(document.getElementById('field2').value);

                        myData = myData.filter(function(d) {
                            return d.date >= date1 && d.date <= date2;
                        });
                    }

                    xScale.domain(myData.map(function(d) { 
                        return d.date; 
                    }));

                    yScale.domain([0, d3.max(myData, function (d) { return d.value; })]);

                    var svg = d3.select('#chart').append('svg')
                                .attr("width", width + margin.left + margin.right)
                                .attr("height", height + margin.top + margin.bottom)
                                .append("g")
                                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                    svg
                        .append('g')
                        .attr("class", "x axis")
                        .attr("transform", "translate(0," + height + ")")
                        .call(hAxis)
                        .selectAll("text")
                        .style("text-anchor", "end")
                        .attr("dx", "-.8em")
                        .attr("dy", "-.55em")
                        .attr("transform", "rotate(-90)" );

                    svg
                        .append('g')
                        .attr("class", "y axis")
                        // .attr('transform', 'translate(35,' + (height - 25) + ')')
                        .call(vAxis)

                    svg
                        .selectAll(".bar")
                        .data(myData)
                        .enter().append("rect")
                        .attr("class", "bar")
                        .style("fill", "steelblue")
                        .attr("x", function(d) { 
                            return xScale(d.date); 
                        })
                        .attr("width", xScale.rangeBand())
                        .attr("y", function(d) { 
                            return yScale(d.value); 
                        })
                        .attr("height", function(d) { 
                            return height - yScale(d.value); 
                        })    
                }
                   d3.json(jsonURL, function(data) {
                    myData = data;
                    myData.forEach(function(d) {
                        d.date  = new Date(d.date);
                        d.value = +d.value;
                    });

                    render(false);
                });

            </script>

            <form name="myform" id="myForm">

        <select id="dropdown1"></select>
        <select id="listbox"></select>
        <br>
            </body>
    <html>
    My json

        [{
          "name": "obs",
          "date": "1451606400",
          "value": "40",
          "attr001": "brs1",
          "attr002": "crs1",
          "attr003": "drs1",
        },
         {
          "name": "qwe",
          "date": "1454371200",
          "value": "140",
          "attr001": "klm1",
          "attr002": "wer1",
          "attr003": "iop1",
        }, {
          "name": "rty",
          "date": "1454371200",
          "value": "40",
          "attr001": "yrs1",
          "attr002": "qws1",
          "attr003": "prs1"
    }]
My js file

$(document).ready(function() {

    $.ajax({
        url: "mydata.json",
        dataType: "json",
        success: function(obj) {
            var jsObject = obj;
            var usedNames = [];

            $('<option>', {
                text: 'Select your Option',
                value: '',
                selected: 'selected',
                disabled: 'disabled'
            }).appendTo('#dropdown1');
            $.each(obj, function(key, value) {
                if (usedNames.indexOf(value.name) == -1) {
                    $("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
                    usedNames.push(value.name);
                }

                $('#dropdown1').change(function() {
                    $('#listbox').empty();

                    $('<option>', {
                        text: 'Select your List Option',
                        value: '',
                        selected: 'selected',
                        disabled: 'disabled'
                    }).appendTo('#listbox');

                    var selection = $('#dropdown1 :selected').text();
                    $.each(jsObject, function(index, value) {
                        if (value['name'] == selection) {
                            var optionHtml = '';
                            for (var i = 1; i <= 20; i++) {
                                var attr = 'attr' + ('000' + i).substr(-3);
                                optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
                            }
                            $('#listbox').append(optionHtml); return false;
                        }
                    });
                });
            });
        }
    });
});
查看全部
weixin_33695450
weixin_33695450
2016/04/08 20:42
  • d3.js
  • html
  • ajax
  • javascript
  • jquery
  • 点赞
  • 收藏
  • 回答
    私信

1个回复