简体   繁体   中英

How can I transfer a variable from Python Flask to JavaScript?

I am developing a simple website with Python Flask and JavaScript for my machine learning project. It has a form which gets data from the user, then predict a target and send it back to the user. I set the action of form as "index", and When the form is submitted the page "index.html" should be loaded. I tried using POST method to get data from JavaScript and it works, but on the other hand, I cannot transfer the answer from Python to JavaScript. My code for POST method is something like this:

@app.route('/',methods = ['POST', 'GET'])
def myFunction():
if request.method == "POST":
    myVariable = request.form["example"]
    answer = myModel.predition(myVariable)

    return redirect(url_for("index"))

else:
    return render_template("myWeb.html")

I tried using GET method in Flask and fetch in JS to transfer the answer but as my answer variable is in myFunction(), I cannot use GET outside of it. Furthermore, when I tried to show a simple string as answer it didn't work. My code was something like this:

@app.route('/index',methods = ['POST', 'GET'])
def answer():
if request.method == 'GET':
    message = {"prediction"}
    return jsonify(message)

and my JS was:

fetch('/index')
    .then(function (response) {
          return response.json();
  }).then(function (text) {
      console.log('GET response:');
      console.log(text); 
  });

I really don't know how should I fix this and show my answer on index.html successfully. I take Internal Server Error on index page.

message = {"prediction"} is a Set that contains your string. As usually sets are not JSON serializable. You have to use a list here message = ["prediction"] (or remove the brackets to return as simply string)

Btw: You're indentation looks broken... Maybe it's a copy&paste issue, but please check if your code is correct indented.

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