холст. js график не будет отображаться для временных и временных данных - PullRequest
0 голосов
/ 17 июня 2020

Пожалуйста, помогите,

Я использую XAMPP 1.7.2, который использует php 5.4. Я использую php для вывода json, что дает результат ниже, хотя есть три поля, которые я использую только два -

{
  "weather": [
    {
      "time": "2020-06-12 19:48:12",
      "temp": "28.4",
      "hum": "72"
    },
    {
      "time": "2020-06-12 19:48:21",
      "temp": "28.4",
      "hum": "72"
    },
    {
      "time": "2020-06-12 19:48:29",
      "temp": "28.4",
      "hum": "72"
    },
    {
      "time": "2020-06-12 19:48:38",
      "temp": "28.4",
      "hum": "72"
    },
    {
      "time": "2020-06-12 19:48:47",
      "temp": "28.4",
      "hum": "72"
    },
    {
      "time": "2020-06-12 19:48:56",
      "temp": "28.4",
      "hum": "72"
    },
    {
      "time": "2020-06-12 19:49:05",
      "temp": "28.4",
      "hum": "72"
    },
    {
      "time": "2020-06-12 19:49:14",
      "temp": "28.4",
      "hum": "72"
    },
    {
      "time": "2020-06-12 19:49:22",
      "temp": "28.4",
      "hum": "71"
    },
    {
      "time": "2020-06-12 19:49:31",
      "temp": "28.4",
      "hum": "72"
    }
  ]
}

И я использую следующий html, чтобы получить эти данные из диаграмма. php и визуализация как холст js диаграмма . Я конвертирую дату в указанный формат, который я тестировал на их веб-сайте. https://canvasjs.com/docs/charts/basics-of-creating-html5-chart/date-time-axis/, где я изменил дату с помощью метода Date.parse (' 04 De c 1995 00:12:00 GMT '), здесь я предоставил образец, который я использовал, и он работал , но не работает с моим кодом . Поскольку я предоставил данные, которые использую, я собираюсь вставить соответствующий код php и javscript.

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

    <script type="text/javascript">
        window.onload = function () {
            var dataPoints = [];
            var chart;
            $.getJSON("chart.php", function (data) {
                //debugger;
                $.each(data.weather, function (key, value) {
                    dataPoints.push({ x: Date.parse(value.time + ' GMT'), y: value.temp });
                    //debugger;
                });

                chart = new CanvasJS.Chart("chartContainer", {
                    title: {
                        text: "Live Chart with dataPoints from External JSON"
                    },
                    // axisX: {
                    //  valueFormatString: "YYYY-MM-DD HH:mm:ss",
                    // },
                    data: [{
                        type: "line",
                        xValueType: "dateTime",
                        dataPoints: dataPoints,
                    }]
                });
                chart.render();
                updateChart();
            });
            function updateChart() {
                $.getJSON("chart.php", function (data) {
                    $.each(data.weather, function (key, value) {
                        dataPoints.push({
                            x: Date.parse(value.time + ' GMT'),
                            y: value.temp
                        });
                    });
                    chart.render();
                    if (dataPoints.length > 15) {
                        dataPoints.shift();
                    }
                    setTimeout(function () { updateChart() }, 1000);
                });
            }
        }
    </script>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="canvasjs.min.js"></script>
</head>

<body>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>

</html>

А вот мой код php, который возвращает json данные

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
//Creating Array for JSON response

$response = array();
// Include data base connect class
$filepath = realpath (dirname(__FILE__));
require_once($filepath."/db_connect.php");
 // Connecting to database 
$db = new DB_CONNECT(); 

 // Fire SQL query to get all data from weather
 $d = $_GET["ID"];
 if($d == null)
 {

    $result = "SELECT * FROM weatherdata where ID > '+$d+' limit 10";
    $result = mysql_query($result) or die(mysql_error());
 }
 else
 {
    $result = mysql_query("SELECT * FROM weatherdata where ID > '+$d+' limit 10") or die(mysql_error());
 }

// Check for succesfull execution of query and no results found
if (mysql_num_rows($result) > 0) {

    // Storing the returned array in response
    $response["weather"] = array();

    // While loop to store all the returned response in variable
    while ($row = mysql_fetch_array($result)) {
        // temperoary user array
        $weather = array();
        $weather["time"] = $row["timestamp"];
        $weather["temp"] = $row["temperature"];
        $weather["hum"] = $row["humidity"];

        // Push all the items 
        array_push($response["weather"], $weather);
    }


    // Show JSON response
    array_push($response["weather"], $jsonarrays);

}   
else 
{
    // If no data is found
    $response["success"] = 0;
    $response["message"] = "No data on weather found";

    // Show JSON response
    echo json_encode($response);
}
?>


...