[英]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.我正在为我的机器学习项目开发一个带有 Python Flask 和 JavaScript 的简单网站。 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.
我将表单的操作设置为“索引”,当提交表单时,应该加载页面“index.html”。 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.
我尝试使用 POST 方法从 JavaScript 获取数据并且它有效,但另一方面,我无法将答案从 Python 转移到 JavaScript。 My code for POST method is something like this:
我的 POST 方法代码是这样的:
@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.我尝试在 Flask 中使用 GET 方法并在 JS 中获取来传输答案,但由于我的答案变量在 myFunction() 中,我不能在它之外使用 GET。 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:我的 JS 是:
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.我真的不知道我应该如何解决这个问题并成功地在 index.html 上显示我的答案。 I take Internal Server Error on index page.
我在索引页面上出现内部服务器错误。
message = {"prediction"}
is a Set that contains your string. message = {"prediction"}
是一个包含您的字符串的集合。 As usually sets are not JSON serializable.通常集合不是 JSON 可序列化的。 You have to use a list here
message = ["prediction"]
(or remove the brackets to return as simply string)您必须在此处使用列表
message = ["prediction"]
(或删除括号以简单地返回字符串)
Btw: You're indentation looks broken... Maybe it's a copy&paste issue, but please check if your code is correct indented.顺便说一句:你的缩进看起来坏了......也许这是一个复制和粘贴问题,但请检查你的代码是否正确缩进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.