![](/img/trans.png)
[英]How would I transfer information like a variable from javascript to python using AJAX and Flask
[英]How can I transfer a variable from Python Flask to JavaScript?
我正在為我的機器學習項目開發一個帶有 Python Flask 和 JavaScript 的簡單網站。 它有一個表單,可以從用戶那里獲取數據,然后預測目標並將其發送回用戶。 我將表單的操作設置為“索引”,當提交表單時,應該加載頁面“index.html”。 我嘗試使用 POST 方法從 JavaScript 獲取數據並且它有效,但另一方面,我無法將答案從 Python 轉移到 JavaScript。 我的 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")
我嘗試在 Flask 中使用 GET 方法並在 JS 中獲取來傳輸答案,但由於我的答案變量在 myFunction() 中,我不能在它之外使用 GET。 此外,當我嘗試顯示一個簡單的字符串作為答案時,它不起作用。 我的代碼是這樣的:
@app.route('/index',methods = ['POST', 'GET'])
def answer():
if request.method == 'GET':
message = {"prediction"}
return jsonify(message)
我的 JS 是:
fetch('/index')
.then(function (response) {
return response.json();
}).then(function (text) {
console.log('GET response:');
console.log(text);
});
我真的不知道我應該如何解決這個問題並成功地在 index.html 上顯示我的答案。 我在索引頁面上出現內部服務器錯誤。
message = {"prediction"}
是一個包含您的字符串的集合。 通常集合不是 JSON 可序列化的。 您必須在此處使用列表message = ["prediction"]
(或刪除括號以簡單地返回字符串)
順便說一句:你的縮進看起來壞了......也許這是一個復制和粘貼問題,但請檢查你的代碼是否正確縮進。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.