Changing value of global javascript variable
I'm attempting to change the value of a global variable inside a javascript function, however, the value does not seem to be taken, and I'm not sure why. (Admittedly, I am not an expe开发者_C百科rienced javascript person.) Here is my code:
var title_chart = "";
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Number of Entries');
jQuery.getJSON('/data/stats.json', function(chart_data) {
title_chart = chart_data.chart_title;
jQuery.each(chart_data.stats, function(index, value){
data.addRows(1);
data.setValue(index, 0, value.chart_label);
});
});
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 450, height: 300, title: title_chart});
}
Thanks!
getJSON
is asynchronous. Do this instead:
jQuery.getJSON('/data/stats.json', function(chart_data) {
var title_chart = chart_data.chart_title;
jQuery.each(chart_data.stats, function(index, value){
data.addRows(1);
data.setValue(index, 0, value.chart_label);
});
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 450, height: 300, title: title_chart});
});
The issue is that getJSON
returns immediately. Only later, when the request completes, is your callback called. In the meantime, chart.draw
may have already run. By moving this code into the callback function, we ensure it runs at the right time. Also note that we can eliminate the global.
精彩评论