Refresh morris chart using javascript

☆樱花仙子☆ 提交于 2019-12-01 13:12:33

问题


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:


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>


来源:https://stackoverflow.com/questions/42198625/refresh-morris-chart-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!