我想把这个JSON数据放到Chart.js图表中:
[
{
"data": "1st",
"count": "166"
},
{
"data": "2nd",
"count": "24"
},
{
"data": "3rd",
"count": "65"
}
]
chart.js之
var pieData = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 40,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Grey"
},
{
value: 166,
color: "#4D5360",
highlight: "#616774",
label: "Blue"
}
];
window.onload = function(){
var ctx = document.getElementById("chart-area").getContext("2d");
window.myPie = new Chart(ctx).Pie(pieData);
};
Javascript加载JSON:
var xmlhttp = new XMLHttpRequest();
var url = "chart.json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].data + arr[i].count;
}
document.getElementById("nooo").innerHTML = out;
}
但这只会将数据放入一个元素中。有没有什么方法可以将数据放入饼图value
和label
值的变量中? (如果我不够清楚,请参阅我的例子) -
var pieData = [
{
value: count,
color:"#F7464A",
highlight: "#FF5A5E",
label: data
},
{
value: count,
color: "#949FB1",
highlight: "#A8B3C5",
label: data
},
{
value: count,
color: "#4D5360",
highlight: "#616774",
label: data
}
];
你会怎么做?
答案 0 :(得分:2)
$.ajax({
url: 'chartpi.php',
success: function (response) {//response is value returned from php
alert(response); //showing response is working
var datachart = JSON.parse(response);
var ctx2 = document.getElementById("chart-area2").getContext("2d");
window.myPie = new Chart(ctx2).Pie(datachart);
}
});