Google linechart visualization chart disappears wh

2019-07-24 02:18发布

问题:

I want to be able to update the line chart of google visualizations. My code was inspired by this Stack Overflow post.

Here is my code in question:

http://jsfiddle.net/YCqyG/5/

You'll see that when you click the button titled "click", the chart suddenly disappears.


UPDATE: When I comment out this line, it appears to be working:

// this.element.html('');

And it does not appear to work for the line chart. Any idea why it won't work for the line chart?

回答1:

There seem to be a few issues around the usage of jQuery selectors in your code; it's somewhat confusing around the sections where you're calling $(element) and $(element)[0] etc. In general I'd avoid jQuery here, the refresh works by replacing both of:

  • add('LineChart', '#mileage') with add('LineChart', 'mileage')
  • $(element)[0] with document.getElementById(element)

Some general advice here:

  • You don't need to clear out the div before re-rendering a chart (i.e.: No need to call this.element.html(''), simple passing in a new data table and re-calling .draw(newDataTable, opts) is fine. Whilst potentially beyond the needs of this post, the new gviz animation functionality is a good example of this (you just call redraw with updated data, and the graph animates the change).
  • Obviously I'm unaware of the full need of your implementation, but I feel like your code may be slightly more involved than you need. Depending on how you get can data sent from your server, you can pretty easily reload a chart. I've given some details in this question, but in brief it looks like this:

    function drawMyChart(dataTable) {
        // convert your dataTable to the right format
        // options here include loading from arrays, json representations of your datatable
        // or something more manual perhaps
        var opts = {height:50, width:50};
        var chart = new google.visualization.LineChart(document.getElementById('vis'));
        chart.draw(dataTable, opts);
    }
    
    function makeAjaxCall() {
        $.ajax({
            url: '/path/to/data/json',
            sucess: drawMyChart(a),
            dataType: 'json' // this is important, have it interpreted as json
        });
    }
    // html somewhere
    <div id='vis'></div>
    <input type='button' onclick='makeAjaxCall()'>Go</input>
    

Hope that helps.