英文:
Passing parameters with flask render_template()
问题
我需要显示一些选择选项。一旦选择了类别,我希望显示另一个选择框来选择子类别。
我的Flask代码
def return_panim():
panim = ["", "טיפול ניקוי עמוק", "טיפול יופי", "טיפול פילינג עמוק", "טיפול לאקנה ולעור בעייתי", "טיפול אנטי אייג'ינג מזוטרפיה", "טיפול אנטי אייג'ינג מיצוק העור"]
data = """
<label>קטגוריה</label>
<select id="subCategory" onchange="loadDoc()">"""
for pan in panim:
data = data + f'<option value="{pan}">{pan}</option>'
data = data + '</select>'
return data
def return_categories():
category_list = ["", "טיפול פנים", "טיפול הסרת שיער", "טיפול הסרת פיגמנטציה", "עיצוב גבות", "מניקור", "פדיקור", "שעווה", "שעווה גברים"]
data = """
<label>תת קטגוריה</label>
<select id="category" onchange="loadDoc()">"""
for category in category_list:
data = data + f'<option value="{category}">{category}</option>'
data = data + '</select>'
return data
@app.route("/appoint", methods=["GET", "POST"])
def apple(name=None):
if request.method == "POST":
r = request.get_data().decode("utf-8")
print(r)
if r == "טיפול פנים":
print(return_panim())
return render_template("appoint.html", data_category=return_categories(), data_subcategory=return_panim())
return render_template("appoint.html", data_category=return_categories())
我的客户端代码
<html>
<head>
</head>
<body>
{{ data_category | safe }}
{{ data_subcategory | safe }}
<script>
function loadDoc() {
let encoder = new TextEncoder();
const xhttp = new XMLHttpRequest();
var sel = document.getElementById("category");
var text = sel.value;
xhttp.open("POST", "https://www.annastudio.beauty/appoint", true);
xhttp.send(encoder.encode(text));
}
</script>
</body>
</html>
当我尝试在没有条件的情况下返回时,像这样
@app.route("/appoint", methods=["GET", "POST"])
def apple(name=None):
return render_template("appoint.html", data_category=return_categories(), data_subcategory=return_panim())
它会呈现两个选择框。
英文:
I need to display some select options. Once the category is chosen, I want to display the subcategory with another select.
My flask code
def return_panim():
panim = ["", "טיפול ניקוי עמוק", "טיפול יופי", "טיפול פילינג עמוק", "טיפול לאקנה ולעור בעייתי", "טיפול אנטי אייג'ינג מזוטרפיה", "טיפול אנטי אייג'ינג מיצוק העור"]
data = """
<label>קטגוריה</label>
<select id="subCategory" onchange="loadDoc()">"""
for pan in panim:
data = data + '<option value=' + '"' + pan + '"' + ">" + '"' + pan + '"' + '</option>'
data = data + '</select>'
return data
def return_categories():
category_list = ["", "טיפול פנים", "טיפול הסרת שיער", "טיפול הסרת פיגמנטציה", "עיצוב גבות", "מניקור", "פדיקור", "שעווה", "שעווה גברים"]
data = """
<label>תת קטגוריה</label>
<select id="category" onchange="loadDoc()">"""
for category in category_list:
data = data + '<option value=' + '"' + category + '"' + '>' + category + '</option>'
data = data + "</select>"
return data
@app.route("/appoint", methods=["GET", "POST"])
def apple(name=None):
if request.method == "POST":
r = request.get_data().decode("utf-8")
print(r)
if r == "טיפול פנים":
print(return_panim())
return render_template("appoint.html", data_category=return_categories(), data_subcategory=return_panim())
return render_template("appoint.html", data_category=return_categories())
My client side
<html>
<head>
</head>
<body>
{{ data_category | safe }}
{{ data_subcategory | safe }}
<script>
function loadDoc() {
let encoder = new TextEncoder();
const xhttp = new XMLHttpRequest();
var sel = document.getElementById("category");
var text = sel.value;
xhttp.open("POST", "https://www.annastudio.beauty/appoint", true);
xhttp.send(encoder.encode(text));
}
</script>
</body>
</html>
When I try to return without condition like so
@app.route("/appoint", methods=["GET", "POST"])
def apple(name=None):
return render_template("appoint.html", data_category=return_categories(), data_subcategory=return_panim())
It renders both selects.
答案1
得分: 1
我不认为你必须为此任务使用Ajax。
以下示例使用了两个字段集。第二个字段集是根据第一个选择元素中的选择而使用JavaScript启用或禁用的。禁用的字段集使用CSS进行隐藏。
如果您不想使用字段集,您可以以相同的方式禁用和启用单个输入字段。
from enum import Enum, unique
from flask import (
Flask,
redirect,
render_template,
request
)
@unique
class Categories(str, Enum):
OPTION1 = "טיפול פנים"
OPTION2 = "טיפול הסרת שיער"
OPTION3 = "טיפול הסרת פיגמנטציה"
OPTION4 = "עיצוב גבות"
OPTION5 = "מניקור"
OPTION6 = "פדיקור"
OPTION7 = "שעווה"
OPTION8 = "שעווה גברים"
@unique
class SubCategories(str, Enum):
OPTION1 = "טיפול ניקוי עמוק"
OPTION2 = "טיפול יופי"
OPTION3 = "טיפול פילינג עמוק"
OPTION4 = "טיפול לאקנה ולעור בעייתי"
OPTION5 = "טיפול אנטי אייג'ינג מזוטרפיה"
OPTION6 = "טיפול אנטי אייג'ינג מיצוק העור"
app = Flask(__name__)
@app.route('/appoint', methods=['GET', 'POST'])
def appoint():
if request.method == 'POST':
category = request.form.get('category', Categories.OPTION1, type=lambda x: Categories[x])
subcategory = request.form.get('subcategory', type=lambda x: SubCategories[x])
print(category.value)
print(subcategory and subcategory.value)
return redirect(request.url)
return render_template(
'appoint.html',
categories=Categories,
subcategories=SubCategories
)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Appoint</title>
<style>
fieldset[disabled] {
display: none;
}
</style>
</head>
<body>
<form method="post">
<fieldset name="basics">
<label for="category">Category</label>
<select name="category" id="category">
{% for cat in categories -%}
<option value="{{ cat.name }}">{{ cat.value }}</option>
{% endfor -%}
</select>
</fieldset>
<fieldset name="extended">
<label for="subcategory">Subcategory</label>
<select name="subcategory" id="subcategory">
{% for cat in subcategories -%}
<option value="{{ cat.name }}">{{ cat.value }}</option>
{% endfor -%}
</select>
</fieldset>
<button type="submit">Submit</button>
</form>
<script>
(function() {
const triggerVal = {{ categories.OPTION1.name | tojson }};
const selectElem = document.getElementById('category');
const fieldsetElem = document.querySelector('fieldset[name="extended"]');
selectElem.addEventListener('change', function() {
fieldsetElem.disabled = this.value !== triggerVal;
});
})();
</script>
</body>
</html>
英文:
I don't think you have to use Ajax for this task.
The following example uses two field sets. The second field set is enabled or disabled with JavaScript depending on the selection made in the first select element. A disabled field set is hidden using CSS.
If you don't want to use a field set, you can disable and enable individual input fields in the same way.
from enum import Enum, unique
from flask import (
Flask,
redirect,
render_template,
request
)
@unique
class Categories(str, Enum):
OPTION1 = "טיפול פנים"
OPTION2 = "טיפול הסרת שיער"
OPTION3 = "טיפול הסרת פיגמנטציה"
OPTION4 = "עיצוב גבות"
OPTION5 = "מניקור"
OPTION6 = "פדיקור"
OPTION7 = "שעווה"
OPTION8 = "שעווה גברים"
@unique
class SubCategories(str, Enum):
OPTION1 = "טיפול ניקוי עמוק"
OPTION2 = "טיפול יופי"
OPTION3 = "טיפול פילינג עמוק"
OPTION4 = "טיפול לאקנה ולעור בעייתי"
OPTION5 = "טיפול אנטי אייג'ינג מזוטרפיה"
OPTION6 = "טיפול אנטי אייג'ינג מיצוק העור"
app = Flask(__name__)
@app.route('/appoint', methods=['GET', 'POST'])
def appoint():
if request.method == 'POST':
category = request.form.get('category', Categories.OPTION1, type=lambda x: Categories[x])
subcategory = request.form.get('subcategory', type=lambda x: SubCategories[x])
print(category.value)
print(subcategory and subcategory.value)
return redirect(request.url)
return render_template(
'appoint.html',
categories=Categories,
subcategories=SubCategories
)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Appoint</title>
<style>
fieldset[disabled] {
display: none;
}
</style>
</head>
<body>
<form method="post">
<fieldset name="basics">
<label for="category">Category</label>
<select name="category" id="category">
{% for cat in categories -%}
<option value="{{ cat.name }}">{{ cat.value }}</option>
{% endfor -%}
</select>
</fieldset>
<fieldset name="extended">
<label for="subcategory">Subcategory</label>
<select name="subcategory" id="subcategory">
{% for cat in subcategories -%}
<option value="{{ cat.name }}">{{ cat.value }}</option>
{% endfor -%}
</select>
</fieldset>
<button type="submit">Submit</button>
</form>
<script>
(function() {
const triggerVal = {{ categories.OPTION1.name | tojson }};
const selectElem = document.getElementById('category');
const fieldsetElem = document.querySelector('fieldset[name="extended"]');
selectElem.addEventListener('change', function() {
fieldsetElem.disabled = this.value !== triggerVal;
});
})();
</script>
</body>
</html>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论