修改 javascript 以维护 Flask 中的 HTML 下拉菜单选择



我有一个简单的 Flask 应用程序,它要求用户从 5 个选项的下拉菜单中选择一个选项。然后提交此选择,运行腌制模型,并生成预测。

我希望用户选择的最新选项在提交表单后在菜单中保持选中状态。我将发布我的烧瓶应用程序 python 脚本,并尝试在我的 .html 文件中强制这种行为。请注意,不会生成任何错误 - 应用程序运行,但javascript的这些部分不起作用。

如果有人能帮助我修复代码,我将不胜感激 - 我是一个 JavaScript 新手,所以我想知道它是否相当简单。

app.py

from flask import Flask, request, render_template
import pickle
import numpy as np
app = Flask(__name__)
@app.route('/')
def home():
return render_template('landing_ex_2.html')
@app.route('/resell', methods=['POST'])
def get_price():
if request.method=='POST':
result=request.form
category = result['category']
pkl_file = open('cat', 'rb')
index_dict = pickle.load(pkl_file)
cat_vector = np.zeros(len(index_dict))
try:
cat_vector[index_dict['category_'+str(category)]] = 1
except:
pass
pkl_file = open('model.pkl', 'rb')
model = pickle.load(pkl_file)
prediction = model.predict(cat_vector.reshape(1, -1))
return render_template('landing_ex_2.html', prediction=prediction)
if __name__ == '__main__':
app.debug = True
app.run()

landing_ex.html:

<!DOCTYPE html>
<html>
<head>
<!-- Form -->
<h3>
<form id = "selling_form" action = "/resell" method="POST">
<p> Select Category :   
<select id = "mySelect" name="category">
<option value="tops">Tops (shirts, blouses, tank tops) </option>
<option value="bottoms">Bottoms (pants, shorts, skirts) </option>
<option value="dresses">Dresses </option>
<option value="outerwear">Outerwear (jackets, sweaters) </option>
<option value="accessories">Accessories (small miscellaneous items) </option>
</select>
<p> <input type ="submit" value="submit" /> </p>
</h3>
<script>
//check if there's an old selection by the user:
if (sessionStorage.getItem("selectedOption")) {
//to set the selected value:
document.getElementById("mySelect").value = sessionStorage.getItem("selectedOption");
}
//this will set the value to sessionStorage only when user clicks submit
document.getElementById("selling_form").addEventListener("submit", () => {
//to get the selected value:
var selectedOption = document.getElementById("mySelect").value;
sessionStorage.setItem("selectedOption", selectedOption);
});
</script>
<!-- Output -->
<p> 
<h2> Your sale prediction is {{ prediction }}</h2>
</p>
</body>
</html>

看起来JS保存和设置所选选项的部分是错误的。您始终存储和设置"tops"这是选择元素本身的值未选择选项。

请尝试改为存储选定的项目索引:

//check if there's an old selection by the user:
if (sessionStorage.getItem("selectedOption")) {
//to set the selected value:
var select = document.getElementById("mySelect");
select.selectedIndex = sessionStorage.getItem("selectedOption"); // set index of selected element
}
//this will set the value to sessionStorage only when user clicks submit
document.getElementById("selling_form").addEventListener("submit", () => {
//to get the selected value:
var select = document.getElementById("mySelect");
sessionStorage.setItem("selectedOption", select.selectedIndex); // store index of selected element
});

最新更新