通过JSON将PHP数组传递到Javascript以更新Google Chart

前端之家收集整理的这篇文章主要介绍了通过JSON将PHP数组传递到Javascript以更新Google Chart前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有三个我用json编码的 PHP数组…因为数组工作正常而省略了额外的PHP代码….此外,为简洁起见,省略了调用谷歌图表的HTML标记
<?PHP
$encoded_line_volume = json_encode($LineVol) . "\n";
$encoded_loan_volume = json_encode($LoanVol) . "\n";
$encoded_cluster_name = json_encode($ClusterLine) . "\n";
?>

我想在Javascript中访问这三个数组来动态更新我的Google Chart.

<script type="text/javascript">

google.load("visualization","1",{packages:["columnchart"]});
google.setOnLoadCallback(drawChart);

var linevol = new Array;  // This would be the first array passed from PHP
var loanvol = new Array;  // This would be the second array passed from PHP
var clusters = new Array; // This would be the third array passed from PHP

function drawChart() {
    var data = new google.visualization.DataTable();

    data.addColumn('string','Cluster');
    data.addColumn('number','Loans');
    data.addColumn('number','Lines');

/* create for loops to add as many columns as necessary */

var len = jsonarray.length;

    data.addRows(len);

for(i=0; i<len; i++) {

data.setValue(i,' '+clusters[i]+'');     /* x-axis */
data.setValue(i,1,linevol[i]);   /* Y-axis category #1*/
data.setValue(i,2,loanvol[i]);   /* Y-axis category #2*/
}
/*********************************end of loops***************************************/
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data,{width: 400,height: 240,is3D: true,title: 'Prospect Population',legend: 'right'});
}
</script>

解决方法

您可能希望它们成为Javascript变量.当您的PHP执行时,它会创建您的Web浏览器然后解释的代码.所以你想用PHP定义javascript字符串.例如:
<script type="text/javascript">
    var encoded_line_volume = <?PHP echo json_encode($LineVol) ?>;
    var encoded_loan_volume = <?PHP echo json_encode($LoanVol) ?>;
    var encoded_cluster_name = <?PHP echo json_encode($ClusterLine) ?>;
</script>

然后这些变量可以被后续的javascript访问.

原文链接:https://www.f2er.com/js/150890.html

猜你在找的JavaScript相关文章