如何将json文件转换为图形?

时间:2019-06-25 02:58:45

标签: php json

我正在尝试读取json编码的页面,从中获取价值,并将其转化为页面上的图形。

这是json文档的样子:

[{"time":"1561430809","ip":"192.168.102.166","waterlevel":null,"station":null,"humidity":null,"temperature":null},{"time":"1561390045","ip":"192.168.103.151","waterlevel":"419","station":"Near the Training Center","humidity":"0","temperature":"0"}]

这是g代码:

<!doctype html>
<html>
 
<head>
  <title>Line Chart | Abaarso school</title>
  <!--For offline ESP graphs see this tutorial https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/ -->
  <script src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>  
  <style>
  canvas{
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
  }
 
  /* Data Table Styling */
  #dataTable {
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
  }
 
  #dataTable td, #dataTable th {
    border: 1px solid #ddd;
    padding: 8px;
  }
 
  #dataTable tr:nth-child(even){background-color: #f2f2f2;}
 
  #dataTable tr:hover {background-color: #ddd;}
 
  #dataTable th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: #4CAF50;
    color: white;
  }
  </style>
</head>
 
<body>
    <div style="text-align:center;"><b>test</b><br></br>Real Time Data: Humidity, Temperature Logging with Graphs</div>
    <div class="chart-container" position: relative; height:350px; width:100%">
        <canvas id="Chart" width="400" height="400"></canvas>
    </div>
<div>
  <table id="dataTable">
    <tr><th>Time</th><th>Water level (ml)</th><th>Temperaure (&deg;C)</th><th>Humidity (%)</th></tr>
  </table>
</div>
<br>
<br>  
 
<script>
//Graphs visit: https://www.chartjs.org
var ADCvalues = [];
var Tvalues = [];
var Hvalues = [];
var timeStamp = [];
function showGraph()
{
    var ctx = document.getElementById("Chart").getContext('2d');
    var Chart2 = new Chart(ctx, {
        type: 'line',
        data: {
            labels: timeStamp,  //Bottom Labeling
            datasets: [{
                label: "water level",
                fill: false,  //Try with true
                backgroundColor: 'rgba( 243,18, 156 , 1)', //Dot marker color
                borderColor: 'rgba( 243, 18, 156 , 1)', //Graph Line Color
                data: ADCvalues,
            },{
                label: "Temperature",
                fill: false,  //Try with true
                backgroundColor: 'rgba( 243, 156, 18 , 1)', //Dot marker color
                borderColor: 'rgba( 243, 156, 18 , 1)', //Graph Line Color
                data: Tvalues,
            },
            {
                label: "Humidity",
                fill: false,  //Try with true
                backgroundColor: 'rgba(156, 18, 243 , 1)', //Dot marker color
                borderColor: 'rgba(156, 18, 243 , 1)', //Graph Line Color
                data: Hvalues,
            }],
        },
        options: {
            title: {
                    display: true,
                    text: "Station A: near the training center"
                },
            maintainAspectRatio: false,
            elements: {
            line: {
                    tension: 0.5 //Smoothening (Curved) of data lines
                }
            },
            scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }]
            }
        }
    });
 
}
 
//On Page load show graphs
window.onload = function() {
  console.log(new Date().toLocaleTimeString());
};
 
//Ajax script to get ADC voltage at every 5 Seconds 
//Read This tutorial https://circuits4you.com/2018/02/04/esp8266-ajax-update-part-of-web-page-without-refreshing/
 
setInterval(function() {
  // Call a function repetatively with 5 Second interval
  getData();
}, 5000); //5000mSeconds update rate
 
function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     //Push the data in array
  var time = new Date().toLocaleTimeString();
  var txt = this.responseText;
  var obj = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
      ADCvalues.push(obj.waterlevel);
      Tvalues.push(obj.temperature);
      Hvalues.push(obj.humidity);
      timeStamp.push(time);
      showGraph();  //Update Graphs
  //Update Data Table
    var table = document.getElementById("dataTable");
    var row = table.insertRow(1); //Add after headings
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    cell1.innerHTML = time;
    cell2.innerHTML = obj.waterlevel;
    cell3.innerHTML = obj.temperature;
    cell4.innerHTML = obj.humidity;
    }
  };
  xhttp.open("GET", "http://abdikani.local.ask.org/json.php", true); //Handle readADC server on ESP8266
  xhttp.send();
}
    
</script>
</body>
 
</html>
 

我没有从本地json页面获取值,因此无法绘制图形。我这是怎么了?我只需要从json编码页面中获取值,然后在折线图上显示它们即可。

这是错误。

Uncaught TypeError: Cannot read property 'skip' of undefined
    at l (Chart.min.js:10)
    at u (Chart.min.js:10)
    at a (Chart.min.js:10)
    at t.getElementsAtEventForMode (Chart.min.js:10)
    at t.handleEvent (Chart.min.js:10)
    at t.eventHandler (Chart.min.js:10)
    at n (Chart.min.js:10)
    at HTMLCanvasElement.x.<computed> (Chart.min.js:10)
133Chart.min.js:10 Uncaught TypeError: Cannot read property 'skip' of undefined
    at l (Chart.min.js:10)
    at u (Chart.min.js:10)
    at a (Chart.min.js:10)
    at t.getElementsAtEventForMode (Chart.min.js:10)
    at t.handleEvent (Chart.min.js:10)
    at t.eventHandler (Chart.min.js:10)
    at n (Chart.min.js:10)
    at HTMLCanvasElement.x.<computed> (Chart.min.js:10)

Json.php中的代码是:

<?php
$dab=new PDO('sqlite:waterlevel');
$st=$dab->prepare('select time, ip, waterlevel, station, humidity, temperature from waterlevel group by station order by time desc limit 100');
$st->execute();
$sv=$st->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($sv);
?>

1 个答案:

答案 0 :(得分:1)

出现此错误是因为您试图访问对象值数组,您拥有多个对象,而不仅仅是一个对象,因此您可能要对其进行迭代。遍历它的一种解决方案是使用forEach()read here)。

您可能还必须更改数据库列以使其不能为空。

<!DOCTYPE html>
<html>
    <head>
        <title>Line Chart | Abaarso school</title>
        <!--For offline ESP graphs see this tutorial https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/ -->
        <script src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
        <meta charset="UTF-8">
        <style>
        canvas{
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
        }

        /* Data Table Styling */
        #dataTable {
            font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }

        #dataTable td, #dataTable th {
            border: 1px solid #ddd;
            padding: 8px;
        }

        #dataTable tr:nth-child(even){background-color: #f2f2f2;}

        #dataTable tr:hover {background-color: #ddd;}

        #dataTable th {
            padding-top: 12px;
            padding-bottom: 12px;
            text-align: left;
            background-color: #4CAF50;
            color: white;
        }
        </style>
    </head>
    <body>
        <div style="text-align:center;"><b>test</b><br></br>Real Time Data: Humidity, Temperature Logging with Graphs</div>
        <div class="chart-container" position: relative; height:350px; width:100%">
            <canvas id="Chart" width="400" height="400"></canvas>
        </div>
        <div>
            <table id="dataTable">
                <tr><th>Time</th><th>Water level (ml)</th><th>Temperaure (&deg;C)</th><th>Humidity (%)</th></tr>
            </table>
        </div>
        <br>
        <br>  

        <script>
        //Graphs visit: https://www.chartjs.org
        var ADCvalues = [];
        var Tvalues = [];
        var Hvalues = [];
        var timeStamp = [];
        function showGraph()
        {
            var ctx = document.getElementById("Chart").getContext('2d');
            var Chart2 = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: timeStamp,  //Bottom Labeling
                    datasets: [{
                        label: "water level",
                        fill: false,  //Try with true
                        backgroundColor: 'rgba( 243,18, 156 , 1)', //Dot marker color
                        borderColor: 'rgba( 243, 18, 156 , 1)', //Graph Line Color
                        data: ADCvalues,
                    },{
                        label: "Temperature",
                        fill: false,  //Try with true
                        backgroundColor: 'rgba( 243, 156, 18 , 1)', //Dot marker color
                        borderColor: 'rgba( 243, 156, 18 , 1)', //Graph Line Color
                        data: Tvalues,
                    },
                    {
                        label: "Humidity",
                        fill: false,  //Try with true
                        backgroundColor: 'rgba(156, 18, 243 , 1)', //Dot marker color
                        borderColor: 'rgba(156, 18, 243 , 1)', //Graph Line Color
                        data: Hvalues,
                    }],
                },
                options: {
                    title: {
                            display: true,
                            text: "Station A: near the training center"
                        },
                    maintainAspectRatio: false,
                    elements: {
                    line: {
                            tension: 0.5 //Smoothening (Curved) of data lines
                        }
                    },
                    scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero:true
                                }
                            }]
                    }
                }
            });

        }

        //On Page load show graphs
        window.onload = function() {
          console.log(new Date().toLocaleTimeString());
        };

        //Ajax script to get ADC voltage at every 5 Seconds 
        //Read This tutorial https://circuits4you.com/2018/02/04/esp8266-ajax-update-part-of-web-page-without-refreshing/

        setInterval(function() {
          // Call a function repetatively with 5 Second interval
          getData();
        }, 5000); //5000mSeconds update rate

        function getData() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    //Push the data in array
                    var time = new Date().toLocaleTimeString();
                    var txt = this.responseText;
                    var obj = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
                    console.log(obj);
                    obj.forEach(function(element_data){
                        console.log(element_data);
                        ADCvalues.push(element_data.waterlevel);
                        Tvalues.push(element_data.temperature);
                        Hvalues.push(element_data.humidity);
                        timeStamp.push(time);
                        showGraph();
                        var table = document.getElementById("dataTable");
                        var row = table.insertRow(1); //Add after headings
                        var cell1 = row.insertCell(0);
                        var cell2 = row.insertCell(1);
                        var cell3 = row.insertCell(2);
                        var cell4 = row.insertCell(3);
                        cell1.innerHTML = time;
                        cell2.innerHTML = element_data.waterlevel;
                        cell3.innerHTML = element_data.temperature;
                        cell4.innerHTML = element_data.humidity;
                    });
                }
            };
            xhttp.open("GET", "http://abdikani.local.ask.org/json.php", true); // Works fine with me using the same json document locally - Handle readADC server on ESP8266
            xhttp.send();
        }
        </script>
    </body>
</html>