简体   繁体   English

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

[英]Passing PHP array into Javascript through JSON to update Google Chart

I have three PHP arrays that I've encoded with json... extra PHP code has been omitted because the arrays work properly.... Additionally, the HTML tags that call the google chart have been omitted for sake of brevity... 我有三个我用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";
?>

I would like to access these three arrays in Javascript to update my Google Chart dynamically. 我想在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>

You probably want them to become Javascript variables. 您可能希望它们成为Javascript变量。 When your php executes, it creates code your web browser then interprets. 当您的PHP执行时,它会创建您的Web浏览器然后解释的代码。 So you want to define javascript strings using php. 所以你想用php定义javascript字符串。 For example: 例如:

<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>

Then those variables are accessible to subsequent javascript. 然后这些变量可以被后续的javascript访问。

This is how can you generate data dynamically from PHP, generate a JSON formatted output properly and read it from JavaScript (JQuery required) and load it to Google Visulization (Charts) API. 这是如何从PHP动态生成数据,正确生成JSON格式的输出并从JavaScript(需要JQuery)读取它并将其加载到Google Visulization(Charts)API。

PHP (Server) Side: PHP(服务器)端:

function returnData() {
    $data = Array ();
    $data [] = Array ("Name", "Value");
    $data [] = Array ("Apple", 5);
    $data [] = Array ("Banana", 3);

    header('content-type: application/json');
    echo json_encode($data);
 }

Javascript (Client) Side: Javascript(客户端)方:

var jsonData = null;

var jsonDataResult = $.ajax({
    url: dataURL,
    dataType: "json",
    async: false,
    success: (
        function(data) {
            jsonData = data;
        })
});

var data = new google.visualization.arrayToDataTable(jsonData);

This is one of the best examples I did which can help you : its tested and working nicely : Create two pages one called index.php and another one called get_json.php : This is not exactly the codes you posted but exactly the same idea and it answers the quetion. 这是我做过的最好的例子之一,它可以帮助你:它经过测试和运行良好:创建两个页面,一个名为index.php,另一个名为get_json.php:这不是你发布的代码,但完全相同的想法和它回答了问题。

the codes for index.php 

    <html>
    <head>
        <title>King Musa Graph</title>
        <!-- Load jQuery -->
        <script language="javascript" type="text/javascript" 
            src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
        </script>
        <!-- Load Google JSAPI -->
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("visualization", "1", { packages: ["corechart"] });
            google.setOnLoadCallback(drawChart);

            function drawChart() {
                var jsonData = $.ajax({
                    url: "get_json.php",
                    dataType: "json",
                    async: false
                }).responseText;

                var obj = jQuery.parseJSON(jsonData);
                var data = google.visualization.arrayToDataTable(obj);

                var options = {
                    title: 'King Musa'
                };

                var chart = new google.visualization.LineChart(
                            document.getElementById('chart_div'));
                chart.draw(data, options);
            }

        </script>
    </head>
    <body>
        <div id="chart_div" style="width: 900px; height: 500px;">
        </div>
    </body>
    </html> 

codes for get_json.php
<?php

    $data = Array ();
    $data [] = Array ("Name", "Value");
    $data [] = Array ("PHP", 78);

    $data [] = Array ("JAVA", 1000);
  $data [] = Array ("HTML", 129);


    $table = json_encode($data);
   // header('content-type: application/json'); 

    echo $table ; // this line is important it should be not disabled 

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM