2012-11-03 43 views
2

得到JSON我對morris.js一個奇怪的錯誤圖形庫morris.js不能從HTML

這部作品在graphs.js

$(document).ready(function() { 
    Morris.Line({ 
    element: 'annual', 
    data: [ 
    {y: '2012', a: 100}, 
    {y: '2011', a: 75}, 
    {y: '2010', a: 50}, 
    {y: '2009', a: 75}, 
    {y: '2008', a: 50}, 
    {y: '2007', a: 75}, 
    {y: '2006', a: 100} 
    ], 
    xkey: 'y', 
    ykeys: ['a'], 
    labels: ['Series A'] 
}); 
}) 

這並不 在相應的HTML graphs.js

$(document).ready(function() { 
    Morris.Line({ 
    element: 'annual', 
    data: $('#logs_chart').data('logs'), 
    xkey: 'y', 
    ykeys: ['a'], 
    labels: ['Series A'] 
}); 
}) 

<div data-logs="[ 
    {y: '2012', a: 100}, 
    {y: '2011', a: 75}, 
    {y: '2010', a: 50}, 
    {y: '2009', a: 75}, 
    {y: '2008', a: 50}, 
    {y: '2007', a: 75}, 
    {y: '2006', a: 100} 
    ]" id="logs_chart"></div> 

我得到

Uncaught TypeError: Cannot call method 'match' of undefined morris.js:316 

Morris.parseDate = function(date) { 
    var isecs, m, msecs, n, o, offsetmins, p, q, r, ret, secs; 
    if (typeof date === 'number') { 
     return date; 
    } 
    m = date.match(/^(\d+) Q(\d)$/); 
Uncaught TypeError: Cannot call method 'match' of undefined 
    n = date.match(/^(\d+)-(\d+)$/); 

已經有人遇到了這一點,並找到了解決辦法?

回答

2

對我來說,解決方案是將json輸出放入HTML末尾的腳本標記中的變量中。

像這樣

<script> 

var json_data = [ 
    {y: '2012', a: 100}, 
    {y: '2011', a: 75}, 
    {y: '2010', a: 50}, 
    {y: '2009', a: 75}, 
    {y: '2008', a: 50}, 
    {y: '2007', a: 75}, 
    {y: '2006', a: 100} 
    ] 

</script> 

,並呼籲在graphs.js這個變量文件

$(document).ready(function() { 
    Morris.Line({ 
    element: 'annual', 
    data: json_data, 
    xkey: 'y', 
    ykeys: ['a'], 
    labels: ['Series A'] 
}); 
}) 
5

充塞在數據日誌中的圖形數據不能正常工作,因爲它是一個字符串。你需要使用JSON.parsejQuery.parseJSON或類似的解析數據。

這也是值得注意的是,你在你的例子已經得到了數據並不是嚴格有效的JSON,你需要逃跑的按鍵,如:

<div data-logs='[ 
    {"y": "2012", "a": 100}, 
    {"y": "2011", "a": 75}, 
    {"y": "2010", "a": 50}, 
    {"y": "2009", "a": 75}, 
    {"y": "2008", "a": 50}, 
    {"y": "2007", "a": 75}, 
    {"y": "2006", "a": 100} 
    ]' id="logs_chart"></div> 

以及相應的HTML:

$(document).ready(function() { 
    Morris.Line({ 
    element: 'annual', 
    data: $.parseJSON($('#logs_chart').data('logs')), 
    xkey: 'y', 
    ykeys: ['a'], 
    labels: ['Series A'] 
    }); 
}) 
+0

感謝您的回覆。這說得通。 –