简体   繁体   中英

Raspberry Pi calling Python script from Ajax

I have a simple python code to test out, test.py

import random
pressure = random.random() * 8
displacement = random.random() * 70

I want to add a simple AJAX code to my .html file to execute this test.py

$.ajax({
type: "POST",
url: "~/test.py",
data: { param: text}
}).done(function( o ) {
   // do something
});

but it doesn't work. Am I doing something wrong?

Raspberry Pi, Raspbian, Apache server

You could try to use Flask to serve:

your test.py code:

import random
from flask import Flask, jsonify
from flask import make_response
app = Flask(__name__)

@app.route("/test", methods=['GET', 'POST'])
def test():
    ret = {
       'pressure' : random.random() * 8,
       'displacement' : random.random() * 70,
    }
    resp = make_response(jsonify(ret))
    resp.headers.set('Access-Control-Allow-Origin',  '*')
    return resp

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

then you run it:

$ pip install Flask
$ python test.py
* Running on http://localhost:5000/

and in the ajax:

$.ajax({
type: "POST",
url: "http://localhost:5000/test",
data: { param: text}
}).done(function( o ) {
   // do something
});

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