再次介绍如何在ajax调用后绘制谷歌图表


Once again about how to plot google chart after an ajax call

编辑开始

由于我没有收到任何答案,我将尝试解释,或者更好的是,当我尝试使用ajax时,显示哪些对我有效(没有ajax),哪些现在不起作用。举例来说,我会把代码的基本部分写下来。

我有两个文件,即index.php和script.php,前者是输入表单,后者绘制图表,后者接收表单中插入的内容,用它进行查询,并返回一个返回到index.php的变量,以便在谷歌中使用。

你来了:

index.php

<?php
    session_start();
?>
<!DOCTYPE html>
<html lang="en">
    <head>
    <!-- Google Charts -->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"],callback:drawChart01});
        google.setOnLoadCallback(drawChart01);
        // CHART 01
        function drawChart01() {
            var data = google.visualization.arrayToDataTable([
                ['Technological Area', 'Number of Publications'],
                <?php echo $_SESSION['techAreas03']; ?>
            ]);
            var options = {
                chartArea: {width:'100%',height:'100%'},
                forceIFrame: 'false',
                is3D: 'true',
                pieSliceText: 'value',
                sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.
                titlePosition: 'none'
            };
            var chart = new google.visualization.PieChart(document.getElementById('tech-areas'));
            chart.draw(data, options);
        }
    </script>
    </head>
    <body>
        <form id="publn-nr-srch" action="script.php" method="post" role="form">
            <input id="publn-in" name="publn-in" placeholder="Publication Number" type="text" required />
            <input id="btn-srch" type="submit" value="Search">
        </form>
        <?php
            if(isset($_SESSION['techAreas03'])){
                echo '<div id="tech-areas"></div>';
            }
        ?>
    </body>
</html>

和script.php:

<?php
session_start();
# Query
$sql = "SELECT techarea FROM $table WHERE publn = :publn";
$q = $conn->prepare($sql);
$q->execute(array(':publn' => $_POST['publn-in']));
while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
    $techAreas00[] = ($r['techarea']);
}
# Separate values of the array that are together in only one field and put them into another array.
$techAreas01 = explode(', ', implode(', ', $techAreas00));
# Count values.
$techAreas02 = array_count_values($techAreas01);
# Sort array.
arsort($techAreas02);
# Transform array in a string that will be used in GOOGLE CHART.
$techAreas03 = implode(', ', array_map(function ($v, $k) { return '['''.$k.''','. $v.']'; }, $techAreas02, array_keys($techAreas02)));
$_SESSION['techAreas03'] = $techAreas03;
# Reload index.php, but now with the variable $techAreas03 that will be used in the head to populate the GOOGLE CHART.
header(Location: index.php);

这项工作很好。

现在,当我尝试使用ajax来避免重新加载index.php时,我无法绘制图表。问题是,在script.php创建变量之前,Google脚本已经加载。关于这个问题的更多信息,请参阅下面的原始答案。

以下是修改页面的代码:

index.php

<?php
    session_start();
?>
<!DOCTYPE html>
<html lang="en">
    <head>
    <!-- Google Charts -->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"],callback:drawChart01});
        google.setOnLoadCallback(drawChart01);
        // CHART 01
        function drawChart01() {
            var data = google.visualization.arrayToDataTable([
                ['Technological Area', 'Number of Publications'],
                <?php echo $techAreas03; ?>
            ]);
            var options = {
                chartArea: {width:'100%',height:'100%'},
                forceIFrame: 'false',
                is3D: 'true',
                pieSliceText: 'value',
                sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.
                titlePosition: 'none'
            };
            var chart = new google.visualization.PieChart(document.getElementById('tech-areas'));
            chart.draw(data, options);
        }
    </script>
    </head>
    <body>
        <form id="publn-nr-srch" action="" method="post" role="form">
            <input id="publn-in" name="publn-in" placeholder="Publication Number" type="text" required />
            <input id="btn-srch" type="submit" value="Search">
        </form>
        <div id="ajax"></div>
    </body>
    <script type="text/javascript">
    $(function(){
        $('form#publn-nr-srch').submit(function(){
            $.ajax({
                url: 'script.php',
                type: 'POST',
                data: $('form#publn-nr-srch').serialize(),
                success: function(response) {
                    $('div#ajax').html(response);
                }
            });
            return false;
        });
    });
    </script>
</html>

这里是script.php:

<?php
session_start();
# Query
$sql = "SELECT techarea FROM $table WHERE publn = :publn";
$q = $conn->prepare($sql);
$q->execute(array(':publn' => $_POST['publn-in']));
while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
    $techAreas00[] = ($r['techarea']);
}
# Separate values of the array that are together in only one field and put them into another array.
$techAreas01 = explode(', ', implode(', ', $techAreas00));
# Count values
$techAreas02 = array_count_values($techAreas01);
# Sort array.
arsort($techAreas02);
# Transform array in a string that will be used in GOOGLE CHART.
$techAreas03 = implode(', ', array_map(function ($v, $k) { return '['''.$k.''','. $v.']'; }, $techAreas02, array_keys($techAreas02)));

我对这个问题进行了研究,发现许多线程都在讨论用ajax绘制图表的回调函数,但如果我们已经有了构建图表的数据。问题是,我没有找到任何特定于我的问题的答案,因为我必须通过ajax发送另一个数据(即发布编号=publn-in)。开始一个查询,这个查询的结果是谷歌图表将使用的数据。

我希望我现在能更容易理解,你们能帮助我。

如前所述,下面有更多信息,您可以随时询问更多信息。

非常感谢!

编辑结束

原始后开始

我有一个表单,可以通过ajax将信息发送到php脚本。

这个脚本获取这些信息,查询数据库,并返回一个数组,我将其转换为字符串。

这个字符串将用于绘制谷歌图表。我搜索了如何在ajax调用后绘制图表,但无法获得预期的结果。

问题是已经加载了,我们必须使用回调来绘制图表。

这是我的代码:

<html>
    <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("visualization", "1", {packages:["corechart"]});
            google.setOnLoadCallback(drawChart04);
            function drawChart04() {
                var data = google.visualization.arrayToDataTable([
                    ['Publication', 'Similarity'],
                    <?php echo $chart; ?>
                ]);
                var options = {
                    chartArea: {width:'80%',height:'80%'},
                    forceIFrame: 'true',
                    titlePosition: 'none',
                    hAxis: {title: 'Most Similar Publications', textPosition: 'none'},
                    legend: {position: 'none'}
                };
                var chart = new google.visualization.LineChart(document.getElementById('sim-curve'));
                chart.draw(data, options);
            }
        </script>
    </head>
    <body>
        <form id="publn-nr-srch" action="" method="post" role="form">
            <input class="form-control" id="publn-in" name="publn-in" placeholder="Publication Number" type="text" value="" required />
            <input id="btn-srch" class="btn btn-sm btn-primary" type="submit" value="&nbsp;Search&nbsp;">
        </form>
        <div id="ajax"></div>
    </body>
    <script type="text/javascript">
    $(function(){
        $('form#publn-nr-srch').submit(function(){
            $.ajax({
                url: '../models/pubSearchScr.php',
                type: 'POST',
                data: $('form#publn-nr-srch').serialize(),
                success: function(response) {
                    $('div#ajax').html(response);
                }
            });
            return false;
        });
    });
    </script>
</html>

脚本运行后,我收到一个变量中的以下字符串(这里一切都运行良好):

$chart = "['1977',8], ['1978',31], ['1979',48], ['1980',34], ['1981',30], ['1982',37], ['1983',28], ['1984',31], ['1985',40], ['1986',32], ['1987',44], ['1988',42], ['1989',45], ['1990',43], ['1991',36], ['1992',31], ['1993',34], ['1994',26], ['1995',25], ['1996',41], ['1997',35], ['1998',27], ['1999',25], ['2000',14], ['2001',31], ['2002',19], ['2003',16], ['2004',21], ['2005',20], ['2006',12], ['2007',16], ['2008',29], ['2009',10], ['2010',13], ['2011',22], ['2012',2], ['2013',2]";

我在谷歌上使用的东西(也可以在上面的头部会话中看到):

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart04);
    function drawChart04() {
        var data = google.visualization.arrayToDataTable([
            ['Publication', 'Similarity'],
            <?php echo $chart; ?>
        ]);
        var options = {
            chartArea: {width:'80%',height:'80%'},
            forceIFrame: 'true',
            titlePosition: 'none',
            hAxis: {title: 'Most Similar Publications', textPosition: 'none'},
            legend: {position: 'none'}
        };
        var chart = new google.visualization.LineChart(document.getElementById('sim-curve'));
        chart.draw(data, options);
    }
</script>

在脚本中,我也有以下在ende中得到响应的变量。在ende中,我可以在屏幕上看到html内容,但不能看到图表:

$output = '
            <!-- Similarity Curve -->
            <div class="col-md-6">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <div class="panel-title">
                            <i class="fa fa-line-chart"></i>
                            Similarity Curve
                        </div>
                    </div>
                    <div class="panel-body">
                        <div id="sim-curve"></div>
                    </div>
                </div>
            </div>';
echo $output;

我理解这个问题,在我运行ajax调用之前,已经加载了带有谷歌图表信息的head,但没有$chart变量。然后,当我开始的时候,一切都很顺利,但图表无法绘制。在我的研究中,我读到了回调函数等,我认为它已经在我的代码中了。如果没有,在我的情况下,到底需要什么?在哪里?在头部还是在html代码的中间,还是在脚本中?

一个建议是:当我在没有ajax的情况下也这样做时,即使用html表单将信息发送到php脚本,然后脚本重定向回文件,一切都很好,因为整个页面都会再次加载头。我的问题是当我必须使用令人惊叹的ajax时。

任何帮助都将不胜感激。非常感谢。

原始POST结束

首先,您应该创建一个函数,用于使用图表输入的数据绘制谷歌图表。

Example: drawChart(inputData) = drawChart04(data);

其次,创建一个存储图表数据的变量:

//var inputData = your data;
var inputData = google.visualization.arrayToDataTable([
        ['Publication', 'Similarity'],
        <?php echo $chart; ?>
    ]);

第三,您必须知道如何在服务器上使用ajax(PHP)返回数据:

Example: dataChart = you query or to do something to get it;
echo json_encode(dataChart); exit; //This is just an example.

第四,您必须知道如何将数据从PHP传递到Javascript。我的意思是,当您收到响应时,您必须知道如何基于响应构建inputData。

$.ajax({url: "....php", type: "POST", dataType: "json", data:{..}})
.done(function(response){
   inputData = response; //You have to convert response to inputData. Maybe Json.parse(response).
   //I don't know, You have to know that you response. So find the best way to create inputData.
   drawChart(inputData);//And finally call this function
});

就是这样。我想你能理解我上面提到的。如果你不能解决这个问题。用我的skype给我发信息。我会帮你修的。SkypeID:jewelnguyen8