在图中使用ajax响应值

时间:2017-08-03 08:20:10

标签: javascript php ajax

我试图从数据库中获取数据,以显示在graph.js图中。 我知道来自ajax的回调是异步的,我试图设置超时,等待响应并将返回值设置为全局变量,但没有任何作用。 如果有人能告诉我这是如何工作的,我将不胜感激!感谢

<body>

<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var response = null;

   var xhr;
   if (window.XMLHttpRequest) { // Mozilla, Safari, ...
       xhr = new XMLHttpRequest();
   } else if (window.ActiveXObject) { // IE 8 and older
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
   }
   xhr.open("POST", "fetch-graph.php", true);
   xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   xhr.send("fetch");
   xhr.onreadystatechange = display_data;
   function display_data() {
       if (xhr.readyState == 4) {
           if (xhr.status == 200) {
               console.log(xhr.responseText);
               response = xhr.responseText;
           } else {
               alert("something went wrong");
           }
       }
   }

    var timerId = setInterval(function() {
        if(response !== null) {
            var chart = new Chart(ctx, {
                // The type of chart we want to create
                type: 'line',

                // The data for our dataset
                data: {
                    labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                    datasets: [{
                        label: "Example Graph 1",
                        borderColor: 'rgb(255, 0, 100)',
                        //data: [45,23,39,12,34,56,67,78,90,78,73,74]
                        data: response
                    }]
                }
            });
            clearInterval(timerId);
        }
    }, 1000);

</script>
</body>

这是php文件,从db获取值:

<?php

$connect = mysqli_connect("localhost", "max", "password", "graph");

if(isset($_POST['fetch'])){

    $sql = "SELECT * FROM graph_data";
    $query = mysqli_query($connect, $sql);

    $row = mysqli_fetch_assoc($query);

    $months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'deb'];

    for ($i = 0; $i<12; $i++){
        echo $row[$months[$i]];
    }
}

2 个答案:

答案 0 :(得分:2)

您也可以在ajax响应中添加。 在js页面中

<script     src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.js">    </script>

$.ajax({
            url: "/your URL",
            type: "post",
            dataType: "json",
            data: send your data what you want to send ,
            success: function (response) {
                if (response) {
                    let data = response;
                    var ctx = document.getElementById("doughutChart");
                    ctx.height = 150;

                    var myChart = new Chart(ctx, {
                        type: 'doughnut',
                        data: {
                            datasets: [{
                                data: data,
                                backgroundColor: [
                                    "rgba(253, 11, 21, 0.9)",
                                    "rgba(0, 123, 255,0.7)"
                                ],
                                hoverBackgroundColor: [
                                    "rgba(253, 11, 21, 0.9)",
                                    "rgba(0, 123, 255,0.7)"
                                ]
                            }],
                            labels: [
                                "Pending",
                                "Completed"

                            ]
                        },
                        options: {
                            responsive: true
                        }
                    });
                }
            }
        });

在动态图中,您必须以数组形式发送值。所以在ajax响应中,我得到了数组中的值并将该数据传递到图表中。

答案 1 :(得分:1)

首先,一旦响应出现,最好立即创建图表。 此图表还需要一个数组,因此您必须将来自php的响应编码为JSON。

<body>

<canvas id="myChart"></canvas>

<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var response = null;

   var xhr;
   if (window.XMLHttpRequest) { // Mozilla, Safari, ...
       xhr = new XMLHttpRequest();
   } else if (window.ActiveXObject) { // IE 8 and older
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
   }
   xhr.open("POST", "fetch-graph.php", true);
   xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   xhr.send("fetch");
   xhr.onreadystatechange = display_data;
   function display_data() {
       if (xhr.readyState == 4) {
           if (xhr.status == 200) {
               console.log(xhr.responseText);
               response = xhr.responseText;
               try{
                    var data = JSON.parse(response)
               }catch(e){
                    alert('Could not parse response from server')
                    return
               }
               createChart(data)
           } else {
               alert("something went wrong");
           }
       }
   }

    function createChart(chart_data){
        var chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                datasets: [{
                    label: "Example Graph 1",
                    borderColor: 'rgb(255, 0, 100)',
                    data: chart_data
                }]
            }
        });
    }

</script>
</body>

在服务器端:

$connect = mysqli_connect("localhost", "max", "password", "graph");

$response = array();

if(isset($_POST['fetch'])){

    $sql = "SELECT * FROM graph_data";
    $query = mysqli_query($connect, $sql);

    $row = mysqli_fetch_assoc($query);

    $months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'deb'];

    for ($i = 0; $i<12; $i++){
        $response[] = $row[$months[$i]];
    }
}

echo json_encode($response);