2012-11-03 21 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

感谢您的回复。这说得通。 –