2014-06-25 313 views
1

使用morris.js在图表上绘制一段时间内的一些统计数据。morris.js解析json字符串错误

$(document).ready(function() { 

    if($('#time-graph').length) { 
    var week_data = <?php echo($stat_array)?>; 
    Morris.Line({ 
     element : 'time-graph', 
     data : week_data, 
     xkey : 'period', 
     ykeys : 'temp_avg', 
     labels : ['temp_avg','temp_avg'], 
     events : ['2014-06-01 00:00:01', '2014-6-30 23:55:55'], 
     ymin : -1.0, 
     ymax : 50.0 
    }); 
    } 

$ stat_array包含一个JSON字符串,即以下列方式格式化,在应用

[{"period":"2014-06-24 18:37:44","temp_avg":"46.845"},{"period":"2014-06-24 18:38:01","temp_avg":"47.28"},{"period":"2014-06-24 18:40:01","temp_avg":"47.185"},{"period":"2014-06-24 18:42:01","temp_avg":"47.4675"},{"period":"2014-06-24 18:44:01","temp_avg":"47.3125"},{"period":"2014-06-24 18:46:01","temp_avg":"48"},{"period":"2014-06-24 18:48:01","temp_avg":"47.2175"},{"period":"2014-06-24 18:50:01","temp_avg":"48"},{"period":"2014-06-24 18:52:01","temp_avg":"48.095"}]; 

以前检索但如图所示波纹管

enter image description here

图表不正确格式化

如果任何人能指出我出错的地方会很棒:D

+0

按F12(显示控制台)。在JavaScript控制台中,它会告诉你什么是语法错误或者什么是失败的。 – Zerquix18

+0

错误控制台中没有任何内容被捕获 –

+0

if($('#time-graph')。length)'返回true,对吗? – Zerquix18

回答

1

其实,你只是想念几件事,首先,删除对象上的;分号。

其次,我不知道它是否是错字,但是您错过了关于$(document).ready({});的收盘。

最后,如果您的数据混乱在一个特定区域,请不要感到惊讶,因为您的数据似乎只在2014-06-24 18:MM:SS之间有所不同。我只是调整了范围,你会清楚地看到线条图。 Sample Output

实施例:

<?php $stat_array = '[{"period":"2014-06-24 18:37:44","temp_avg":"46.845"},{"period":"2014-06-24 18:38:01","temp_avg":"47.28"},{"period":"2014-06-24 18:40:01","temp_avg":"47.185"},{"period":"2014-06-24 18:42:01","temp_avg":"47.4675"},{"period":"2014-06-24 18:44:01","temp_avg":"47.3125"},{"period":"2014-06-24 18:46:01","temp_avg":"48"},{"period":"2014-06-24 18:48:01","temp_avg":"47.2175"},{"period":"2014-06-24 18:50:01","temp_avg":"48"},{"period":"2014-06-24 18:52:01","temp_avg":"48.095"}]'; ?> 

<div id="time-graph"></div> 

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> 
<script src="http://cdn.oesmith.co.uk/morris-0.4.1.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
    Morris.Line({ 
     element: 'time-graph', 
     data: <?php echo $stat_array; ?>, 
     xkey: 'period', 
     ykeys: ['temp_avg'], 
     labels: ['temp_avg'], 
     events : ['2014-06-24 18:00:00', '2014-6-24 18:59:59'], 
     ymin : -1.0, 
     ymax : 50.0 
    }); 
}); 
</script>