gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:12:52 26 4
gpt4 key购买 nike

我有三个用 json 编码的 PHP 数组...省略了额外的 PHP 代码,因为数组可以正常工作...此外,为简洁起见,省略了调用 google 图表的 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, 0, ' '+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 执行时,它会创建您的网络浏览器然后解释的代码。所以你想使用 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 访问。

关于php - 通过 JSON 将 PHP 数组传递到 Javascript 以更新 Google Chart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1698801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com