Refresh morris chart using javascript

2020-03-31 07:26发布

I have this morris chart that I would like to refresh using a javascript function. So I then can add a href link on the page that contains that javascript that will refresh the morris chart.

<script type="text/javascript">
    $.get('@Url.Action("GetData")', function (result) {
        Morris.Line({
            element: 'samplechart',
            data: result,
            xkey: 'period',
            ykeys: ['a', 'b'],
            labels: ['YES', 'NO'],
            xLabelAngle: 60,
            parseTime: false,
            resize: true,
            lineColors: ['#32c5d2', '#c03e26']
        });
    });
</script>

How would that javascrip funcion look and how do I call it?

1条回答
神经病院院长
2楼-- · 2020-03-31 08:08

You can create a function that initialize your Morris Line Chart without the data: initMorris. Then to set the data in your chart, on page load or on link clicked, call the function getMorris that gets the data and set the data to the chart setMorris using the built-in setData function of the Morris Line.

Please try the snippet below (for the example, I created a getMorrisOffline function. To get data with ajax, use getMorris instead in page load and in the link event onclick):

var morrisLine;
initMorris();
//getMorris(); 
getMorrisOffline();

function initMorris() {
   morrisLine = Morris.Line({
    element: 'samplechart',
    xkey: 'period',
    ykeys: ['a', 'b'],
    labels: ['YES', 'NO'],
    xLabelAngle: 60,
    parseTime: false,
    resize: true,
    lineColors: ['#32c5d2', '#c03e26']
  });
}

function setMorris(data) {
  morrisLine.setData(data);
}

function getMorris() {
  $.get('@Url.Action("GetData")', function (result) {
    setMorris(result);      
  });
}

function getMorrisOffline() {
 var lineData = [
    { period: '2006', a: 100, b: 90 },
    { period: '2007', a: 75,  b: 65 },
    { period: '2008', a: 50,  b: 40 },
    { period: '2009', a: 75,  b: 65 },
    { period: '2010', a: 50,  b: 40 },
    { period: '2011', a: 75,  b: 65 },
    { period: '2012', a: 100, b: 90 }
  ];
  setMorris(lineData);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css" rel="stylesheet" />

<div id="samplechart"></div>
<a href="#" onclick="getMorrisOffline();">Refresh Morris</a>

查看更多
登录 后发表回答