我正在尝试从 PhP 模块动态获取数据,将其作为 JSON 数据加载到 JavaScript 中,并使用该数据使用 HighCharts 生成饼图。当我使用一些静态数据时,饼图可以正确生成,但当我解析 JSON 数据并将其作为 Highchart 系列对象的输入时,饼图不会加载。我确信这与输入 Highcharts 时的数据格式有关,但我现在无法弄清楚这一点:(所以我想联系你们。我已在此处附加了代码和示例php模块生成的json输出供您引用。
从 PhP 模块生成的示例 JSON 输入:[{"skill":"html","count":"158"},{"skill":"css","count":"134"}]。需要解析此 JSON 输入并将其作为输入提供给我的 HighCharts 系列对象,以生成将“html”和“css”显示为饼图切片的饼图。
如有任何指导,我们将不胜感激。
谢谢。
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Top Skills Analytics</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="highcharts.js"></script>
</head>
<body>
<table>
<tr>
<td colspan="2" align="center"><u><b><font size="4">Top Skills Analysis</font></b></u>
</td>
</tr>
<tr>
<td>
<div id="container" style="height: 500px; width: 500px; margin-bottom: 1em;"></div>
</td>
</tr>
</table>
<script type="text/javascript">
// Creates the HighChart using the dynamically generated data from PhP module
function loadCharts() {
// Parses the JSON data and returns an array of an array
var result = [];
// json from php is like : [{"skill":"html","count":"158"},{"skill":"css","count":"134"}]
$.getJSON('test.php', function (json) {
$.each(json, function (i, entry) {
result.push(entry.skill, entry.count);
});
});
//result = [["html",158],["css",134]]; --> this works
var options1 = {
"series": [{
"name": "Jobs",
"type": "pie",
"sliced": true,
"data": result, // works when populated with static value like [["html",158],["css",134]]
"pointWidth": 15,
"color": "#C6D9E7",
"borderColor": "#8BB6D9",
"shadow": true,
}],
"title": {
"text": "Top Skills Analytics"
},
"legend": {
"layout": "vertical",
"style": {
"left": "auto",
"bottom": "auto",
"right": "auto",
"top": "auto"
}
},
"chart": {
"renderTo": "container"
},
"credits": {
"enabled": false
}
};
var chart1 = new Highcharts.Chart(options1);
}
// Load the charts when the webpage loads for the first time
$(document).ready(function () {
loadCharts();
});
</script>
</body>
最佳答案
它适用于静态数据,因为计数是一个 int
["html",158]
它不适用于动态数据,因为它返回字符串计数
{"skill":"html","count":"158"}
注意到第二个代码行周围的双引号了吗? 在将字符串传递给 highcharts 之前,您需要在 php 或 javascript 中将字符串转换为 int
还有一件事,如果你运行代码 highcharts 应该提示错误
Uncaught Highcharts error #14: www.highcharts.com/errors/14
如果您访问该链接,它基本上说明了有关字符串的相同内容。
代码还有一个问题
[["html",158],["css",134]]
正如你在这里看到的,我们有一个数组数组,当我们使用字符串到 int 解析运行代码时,我们得到
["html", 158, "css", 134]
注意到问题了吗?我们有一个包含四个元素的数组。 您需要做的是:
result.push([entry.skill, entry.count]);
将两个元素的数组插入结果变量,不要忘记 count 必须是 int
关于php - 解析 JSON 数据时 Highcharts 数据显示问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12420262/