我想通过ajax将jsonData加载到chart.js对象中。
我的问题是将jsondata作为字符串引用到chart.js
我认为ajax()。responseText检索一个字符串,但chart.js数据需要一个数组?
我也在使用谷歌图表,但效果非常好。
这是我的代码:
<html>
<head>
<script type="text/javascript" src="./jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="./jslib.js"></script>
<script type="text/javascript" src="./Chart.min.js"></script>
</head>
<body>
<div class="container">
<h2>Chart Test</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
<script type="text/javascript">
var jsonData = $.ajax({
type: "POST",
data: { "ibrconfig_id": 26},
url: "./ibrlib.php",
dataType:"json",
async: false
}).responseText;
//document.write(jsonData);// this returns: { labels: ["1","2"], datasets: [ { label: "Taster", data: [0,0], backgroundColor: "rgba(153,255,51,0.6)" } ] }
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx,
{
type: 'bar',
data: jsonData
});
/*
This works very fine
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx,
{
type: 'bar',
data: { labels: ["1","2"], datasets: [ { label: "Taster", data: [0,0], backgroundColor: "rgba(153,255,51,0.6)" } ] }
});
*/
</script>
</body>
</html>
我该如何处理? 非常感谢你的时间!
答案 0 :(得分:1)
好的我明白了。谢谢你andr1o
我的jsonData错了。
{ labels: ["1","2"], datasets: [ { label: "Taster", data: [0,0], backgroundColor: "rgba(153,255,51,0.6)" } ] }
没有我把它改成
{ "labels": ["1","2"], "datasets": [ { "label": "Taster", "data": [0,0], "backgroundColor": "rgba(153,255,51,0.6)" } ] }
答案 1 :(得分:0)
使用JSON.parse(jsonData)
从json字符串