AJAX displaying values from two different function

2019-05-09 22:43发布

问题:

I have successfully plotted a real-time graph using HighCharts, Flask and Python. A javascript file(highcharts.js) takes values from a (route of a) function in python and continues to fetch updated data from it using AJAX. Then the graph is rendered in a container div in HTML. This worked well with a single graph on the page.

The problem is that when I tried to make a second graph to plot values from another python function(which has other values) using a second javascript file to plot the graph and rendering the graph in another container div, both the values of the first function(for the first graph) and the second function are being plotted in the second graph and the first graph is blank.

There are the two functions in my python file which get two different value sets(the live_data() function is for the first graph and the temp_data() is for the second graph):

@app.route('/live-data')
def live_data():
    lux=readLight() #gets value of light sensor
    # Create a PHP array and echo it as JSON
    data1 = [time() * 1000,lux]
    response1 = make_response(json.dumps(data1))
    response1.content_type = 'application/json'
    return response1

@app.route('/liveTempData')
def temp_data():
    humidity,temperature = Adafruit_DHT.read_retry(11, 4)
    print('Temp={0:0.1f}*C'.format(temperature))
    data2 = [time() * 1000,temperature]
    response2 = make_response(json.dumps(data2))
    response2.content_type = 'application/json'
    return response2

highcharts.js(this gets the values from the /live-data route which is the first function) :

var chart1;

/**
 * Request data from the server, add it to the graph and set a timeout
 * to request again
 */
function requestLightData() {
    $.ajax({
        url: '/live-data',
        success: function(point) {
            var series = chart.series[0],
                shift = series.data.length > 20; // shift if the series is
                                                 // longer than 20

            // add the point
            chart.series[0].addPoint(point, true, shift);

            // call it again after one second
            setTimeout(requestLightData, 1000);
        },
        cache: false
    });
}

$(document).ready(function() {
    chart1 = new Highcharts.Chart({
        chart: {
            //render to div data-container in HTML
            renderTo: 'data-container',
            defaultSeriesType: 'spline',
            events: {
                load: requestLightData
            }
        },
        title: {
            text: 'Luminosity Values'
        },
        xAxis: {
            type: 'datetime',
            tickPixelInterval: 150,
            maxZoom: 20 * 1000
        },
        yAxis: {
            minPadding: 0.2,
            maxPadding: 0.2,
            title: {
                text: 'Values',
                margin: 80
            }
        },
        credits: {
        enabled: false
       },
        series: [{
            name: 'Light',
            data: []
        }]
    });
});

Code snippet from highchartsTemp.js(this gets the values from the /liveTempData route which is the second function) :

var chart;

/**
 * Request data from the server, add it to the graph and set a timeout
 * to request again
 */
function requestData() {
    $.ajax({
        url: '/liveTempData',
        success: function(point) {
            var series = chart.series[0],
                shift = series.data.length > 20; // shift if the series is
                                                 // longer than 20

            // add the point
            chart.series[0].addPoint(point, true, shift);

            // call it again after one second
            setTimeout(requestData, 1000);
        },
        cache: false
    });
}

$(document).ready(function() {
    chart = new Highcharts.Chart({
        chart: {
            //render to div data-container2 in HTML
            renderTo: 'data-container2',
            defaultSeriesType: 'spline',
            events: {
                load: requestData
            }
        },

I have added only a code snippet for highchartsTemp.js because it is almost the same as the highcharts.js, only the function name, url, chart variable have been changed besides some labeling attributes of the graph. Code snippet of html where the charts are being rendered:

 <div class="row">
      <!-- first graph -->
      <div class="container-fluid" id="data-container"></div>

    </div>

      <div class="row">
       <!-- first graph -->
      <div class="container-fluid" id="data-container2"></div>

    </div>

Here is what being being displayed:

And here is what is being shown on the terminal when I run the python script:

192.168.100.4 - - [03/Apr/2018 21:25:35] "GET /live HTTP/1.1" 200 -
192.168.100.4 - - [03/Apr/2018 21:25:35] "GET /static/js/highcharts.js HTTP/1.1" 200 -
192.168.100.4 - - [03/Apr/2018 21:25:35] "GET /static/js/highchartsTemp.js HTTP/1.1" 200 -
192.168.100.4 - - [03/Apr/2018 21:25:40] "GET /live HTTP/1.1" 200 -
192.168.100.4 - - [03/Apr/2018 21:25:41] "GET /live-data?_=1522790899360 HTTP/1.1" 200 -
Temp=27.0*C
192.168.100.4 - - [03/Apr/2018 21:25:42] "GET /liveTempData?_=1522790899379 HTTP/1.1" 200 -
192.168.100.4 - - [03/Apr/2018 21:25:42] "GET /live-data?_=1522790900414 HTTP/1.1" 200 -
Temp=26.0*C
192.168.100.4 - - [03/Apr/2018 21:25:43] "GET /liveTempData?_=1522790900967 HTTP/1.1" 200 -
192.168.100.4 - - [03/Apr/2018 21:25:43] "GET /live-data?_=1522790901451 HTTP/1.1" 200 -
Temp=26.0*C
192.168.100.4 - - [03/Apr/2018 21:25:45] "GET /liveTempData?_=1522790902535 HTTP/1.1" 200 -
192.168.100.4 - - [03/Apr/2018 21:25:45] "GET /live-data?_=1522790902547 HTTP/1.1" 200 -
Temp=26.0*C
192.168.100.4 - - [03/Apr/2018 21:25:46] "GET /liveTempData?_=1522790904108 HTTP/1.1" 200 -
192.168.100.4 - - [03/Apr/2018 21:25:46] "GET /live-data?_=1522790904120 HTTP/1.1" 200 -
Temp=26.0*C

The output on the terminal shows that data from both the routes /liveTempData and /live-data are being received. But data from those routes are being rendered to the same chart.

回答1:

I have been able to solve it. Actually I didn't use my variable chart1 correctly for the function below. It has t be changed as such:

var chart1;

/**
 * Request data from the server, add it to the graph and set a timeout
 * to request again
 */
function requestLightData() {
    $.ajax({
        url: '/live-data',
        success: function(point) {
            var series = chart1.series[0],
                shift = series.data.length > 20; // shift if the series is
                                                 // longer than 20

            // add the point
            chart1.series[0].addPoint(point, true, shift);

            // call it again after one second
            setTimeout(requestLightData, 1000);
        },
        cache: false
    });
}

I also merged the two js scripts into, ie I added all that was in highchartsTemp.js into highcharts.js and removed the script highchartsTemp.js from my HTML file.