简体   繁体   中英

Reading values from page in javascript

I'm new to JavaScript and HTML in general so I may have some silly questions...

I'm using Flask to display a graph with some values from a sensor on a Raspberry pi3. The sensor is connected through a serial port. I want to pass the values I'm reading from the serial port to the index.html, that is the template where I have the javascript code for the graph (made with Rgraph).

This is the main.py with flask and the port reading.

from flask import Flask,render_template
import serial

app = Flask(__name__)
ser = serial.Serial('/dev/ttyACM0', 9600)

@app.route('/')
def hello_world():
return render_template("index.html")

#here I read one value from the serial port
@app.route('/getdata')
def test():
    return ser.readline()

if __name__ == '__main__':
    app.run()

The index.html template that I'm trying to use is this here (on github). The javascript generates some random number (from line 66 to 72) but I want it to read a number from the page '/getdata' instead and push that in the data array.

I thought about using the GET-POST methods but it gets quite complicated. Maybe there's an easier solution? Or, maybe (but I think it's impossible), I could read the serial port directly from the javascript? Or, maybe , I'm doing everything wrong and I need to throw everything out of the window?

Once flask renders the template there is not much you can do. It doesn't really support push requests (at least not as far I can tell) but doing an Ajax request isn't hard

ajax_params = {
        url: '/getdata',
        type: 'GET',
        cache: false,
        dataType: 'json',
        error: function(jqXHR, status, error) {
            console.log("Ajax error " + error);
            console.log("status " + status);
            console.log(jqXHR);
        },
        success: datacb
    };

function datacb (resp, status, jqXHR) {
     /* update code here */
     console.log(resp);

     /* you may want to sleep here */

     $.ajax(ajax_params);
}

$.ajax(ajax_params);

Unless you want to update the data without reloading the index.html page, you might try something like the following:

from flask import Flask,render_template
import serial

app = Flask(__name__)
ser = serial.Serial('/dev/ttyACM0', 9600)

@app.route('/')
def hello_world():
    servalue = test();
    return render_template("index.html", value=servalue)

#here I read one value from the serial port
@app.route('/getdata')
def test():
    return ser.readline()

if __name__ == '__main__':
    app.run()

If you want to update the data without reloading the index page, you'll probably have to use AJAX, as @debhand suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM