我尝试根据本指南解析php文件中构建的JSON数据:
https://google-developers.appspot.com/chart/interactive/docs/php_example?hl=en
我已经以一种很好的方式创建了我的JSON但是当我使用这段代码时,似乎它没有很好地读取JSON:
function drawChart() {
var jsonData = $.ajax({
url: "loader.php",
dataType:"json",
async: false
}).responseText;
我认为JSON密钥中的双引号存在一些问题,因为在this example中Javascript对象没有引号。所以我应该错过什么?
我的脚本代码是:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
dataType:"json",
url: "loader.php",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {title: 'Results', width: 400, height: 240});
}
</script>
我的loader.php
返回的源代码是:
{"cols":
[{"label":"Sources","type":"string"},
{"label":"Count","type":"number"}],
"rows":
[{"c":[{"v":"web"},{"v":"4757"}]},
{"c":[{"v":" iPhone"},{"v":"4324"}]},
{"c":[{"v":"Android"},{"v":"3294"}]},
{"c":[{"v":"BlackBerry\u00ae"},{"v":"2336"}]},
{"c":[{"v":"Instagram"},{"v":"951"}]}
]}
注意:图表加载良好且没有错误但不加载JSON。它说:其他100%。因此标签和行都没有正确加载。
答案 0 :(得分:0)
不得引用这些值。删除引号,例如
var jsonData={"cols":
[{"label":"Sources","type":"string"},
{"label":"Count","type":"number"}],
"rows":
[{"c":[{"v":"web"},{"v":4757}]},
{"c":[{"v":" iPhone"},{"v":4324}]},
{"c":[{"v":"Android"},{"v":3294}]},
{"c":[{"v":"BlackBerry"},{"v":2336}]},
{"c":[{"v":"Instagram"},{"v":951}]}
]};
图表正在运作。
NB :请注意BlackBerry \ u00ae,你的loader.php中有一些解码/编码问题(但这不是造成问题的原因)