我想在饼图中显示数据。以JSON
格式从服务器检索数据,即单int
个值,我想使用饼图显示它。假设数据为66
,那么我想在饼图中显示66%
已满。
我已检索到数据,但无法在javascript中找到接受数据的功能
对于Ex。 :
$(function(){
$("#doughnutChart").drawDoughnutChart([
{ title: "Full", value: 66, color: "#FC4349" },
{ title: "Empty", value: 34, color: "#6DBCDB" },
]);
});`
然后我不想在上面的函数中定义值,而是希望接受来自服务器的值并在饼图中显示。
index.html中的我添加了声明
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON('http://api.thingspeak.com/channels/79448/feed/last.json?callback=?', function(data){
$("div").append(data.field1 + " ");
});
**var x=data.field1;**
});
});
</script>
这是我的index.js文件:
$("#doughnutChart").drawDoughnutChart( dataFromServer);
`$(function(){
`$("#doughnutChart").drawDoughnutChart([
{ title:"Full" value: dataFromServer.y1, color: "#FC4349" },
{ title: "Empty" value: dataFromServer.y2, color: "#6DBCDB" },
]);
});`
`var formattedData = [];`
//“dataFromServer”包含一组格式不同的对象
for ( var i = 0; i < dataFromServer.length; i++ ){
formattedData.push({
value: dataFromServer[i].y,
});
}
$("#doughnutChart").drawDoughnutChart( formattedData );
所以请告诉我这是我应该写在index.js文件中的方式??? dataFromServer.y1 = x; 请建议我正确的方法。
答案 0 :(得分:0)
这取决于您的数据形式。一个;;你要做的是使用变量而不是文字。例如,如果您的数据是具有标题,值和颜色的对象数组,则可以调用:
// "dataFromServer" is an array of appropriately formatted objects
$("#doughnutChart").drawDoughnutChart( dataFromServer);
另一方面,如果你有一个复杂的对象需要映射,你可以这样明确地做:
// "dataFromServer" contains all of the right data, but in different locations
$("#doughnutChart").drawDoughnutChart([
{ title: dataFromServer.x1, value: dataFromServer.y1, color: dataFromServer.z1 },
{ title: dataFromServer.x2, value: dataFromServer.y2, color: dataFromServer.z2 },
]);
您很可能会有一个不同格式的对象数组,您可能希望将其转换为以这种方式格式化的对象数组,在这种情况下,您需要从服务器循环对象并创建新变量来自他们:
// formattedData is the array that will be passed into the chart
var formattedData = [];
// "dataFromServer" contains an array of differently-formatted objects
for ( var i = 0; i < dataFromServer.length; i++ ){
formattedData.push({ title: dataFromServer[i].x,
value: dataFromServer[i].y,
color: dataFromServer[i].z });
}
$("#doughnutChart").drawDoughnutChart( formattedData );
<强>附录:强>
评论澄清后,我正在添加以下内容。假设Title和Color值是静态的(即不是来自数据库),您可以简单地插入整数&#34;值&#34;直接进入代码,如下:
// "mySanFranciscoDataValue" is the single integer you're trying to insert
// into the chart. Simply reference it directly, whether it's a
// variable or a function. Presumably you will have two of them,
// one for each city, so I've included a "myNewYorkDataValue" too.
$("#doughnutChart").drawDoughnutChart([
{ title: "San Francisco", value: mySanFranciscoDataValue, color: "#FC4349" },
{ title: "New York", value: myNewYorkDataValue, color: "#6DBCDB" },
]);