2014-06-25 551 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>