编程语言
首页 > 编程语言> > javascript-再说一次如何在ajax调用后绘制Google图表

javascript-再说一次如何在ajax调用后绘制Google图表

作者:互联网

开始编辑

由于我没有收到任何答案,因此我将尝试解释,或者更好地显示对我有用的内容(没有ajax),并且当我尝试使用ajax时现在不起作用.正如示例所讲的,我将写下代码的本质部分.

我有两个文件,分别是index.php(在哪里是输入表单以及在哪里绘制图表)和script.php(接收在表单中插入的内容),使用它进行查询并返回一个返回index.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 $_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),开始查询,而该查询的结果就是由Google图表使用.

我希望我现在可以更清楚一些,希望你们能帮助我.

如前所述,下面有更多信息,您随时可以提出更多要求.

非常感谢!

编辑结束

原始帖子开始

我有一种表单,可以用来通过ajax将信息发送到php脚本.

该脚本获取此信息,查询数据库并给我返回一个数组,该数组以字符串形式转换.

该字符串将用于绘制Google图表.
我搜索了如何在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]";

我在google资料中使用的内容(也可以在上方看到-):

<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调用之前,已经带有$chart变量的Google图表信息的头部已经加载.然后,当我启动它时,一切都会顺利进行,但是无法绘制图表.在我的研究中,我读到了有关回调函数等的信息,我认为它已经存在于我的代码中.如果没有,那么我的情况和位置到底需要什么?还是在HTML代码的开头或中间,还是在脚本中?

一个建议:当我不使用ajax进行相同操作时,即使用将信息发送到php脚本的html表单,然后将该脚本重定向回该文件,一切正常,因为头部将再次加载整个页面.我的问题是,当我不得不使用惊人的ajax时.

任何帮助将不胜感激.
提前谢谢了.

原始发布结束

解决方法:

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

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

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

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

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

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

标签:ajax,google-visualization,javascript,php
来源: https://codeday.me/bug/20191121/2048968.html