我正在尝试使用AmCharts使用数组创建条形图,该数组是从localStorage检索的较大JSON对象的一部分。基本上,我所做的是检索JSON字符串,将其解析回JSON对象,搜索我正在处理的特定数组(“结果”),搜索该数组以寻找我正在寻找的结果(通过“id” ),然后从该特定结果中获取我需要的数组(“得分”)。然后,我使用该数组作为AmChart代码的输入。
我用另一个样本数组(在代码中定义)测试了AmChart代码,它运行正常。但是,当我尝试从localStorage检索时,我无法显示图表。有什么想法为什么?有问题的代码在这里:
//retrieve initial results response from localstorage
var search_results = localStorage.getItem("results_response");
//convert retrieved string back to JSON array
var search_results_object = JSON.parse(search_results); //search_results_objects is now a JSON array
var results = search_results_object.results; //pull out results array
//get venue_id of detail page from local storage
var ven_id = localStorage.getItem("country_id");
//search JSON response for venue ID
var chartDataResults = [];
var searchField = "id";
var searchVal = ven_id;
for (var i=0 ; i < results.length ; i++)
{
if (results[i][searchField] == searchVal) {
chartDataResults.push(results[i]);
}
}
var chartDataInput = chartDataResults.scores;
//this all works:
var chartData = chartDataInput;
var chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
chart.rotate = true;
var graph = new AmCharts.AmGraph();
graph.valueField = "score";
graph.type = "column";
chart.addGraph(graph);
var categoryAxis = chart.categoryAxis;
categoryAxis.autoGridCount = false;
categoryAxis.gridCount = chartData.length;
categoryAxis.gridPosition = "start";
categoryAxis.labelRotation = 90;
graph.fillAlphas = 0.8;
chart.write('chartdiv');
最近,Chrome中的开发控制台告诉我“Uncaught TypeError:无法读取未定义的属性'长度'”。图表也没有呈现。思考?我感谢任何帮助。
答案 0 :(得分:0)
您的代码因此而失败:
var chartDataInput = chartDataResults.scores;
chartDataResults
是您声明的数组,而不是对象。根据{{3}},您可以直接传递chartDataResults
,因为它的格式正确,例如[{title:"sample 1",value:130},{title:"sample 2",value:26}];
。
如果是这样 - 尝试替换:
var chartDataInput = chartDataResults.scores;
//this all works:
var chartData = chartDataInput;
带
var chartData = chartDataResults;
如果chartDataResults数组的格式不正确,则需要在该循环中构造它。类似的东西:
for (var i=0 ; i < results.length ; i++) {
if (results[i][searchField] == searchVal) {
var aResult = new Object();
aResult.title = results[i].title; // or results[i]['title']
aResult.value = parseInt(results[i].value); // or results[i]['value']
chartDataResults.push(aResult);
}
}
我推测你的json对象中有.title
和.value
。如果不是 - 相应地更换它们。如果你不确定:)他们有什么属性 - 将它们打印到控制台并检查它们。