前の選択に基づいて複数のドロップダウンメニューを動的に更新するにはどうすればよいですか? (このコードには3つのドロップダウンしかありませんが、結局2つを追加します)。複数の(複数の)ドロップダウン選択肢/オプション(Flask、python、Ajax)を動的に取り込みます
問題:2番目のドロップダウン(category_2)が正しく最初の値を読み込み、最初の値と等しくない値のリスト(json経由)を渡します。しかし、category_1とcategory_2の両方の値を3番目のドロップダウンに渡す方法を理解できません。
(テンプレートページとフォームコードを含めることができますが、今は2つの変数またはjson文字列を送信する適切な方法を診断するのに役立つと考えています)。ここで
が私のコードです:フラスコインポートフラスコ、要求、render_template、make_response から App.py 輸入JSON フォーム輸入TestFormを 輸入JSONから
app = Flask(__name__)
app.config['SECRET_KEY'] = "my precious"
extra = ['Product_Type','Geography','Third']
@app.route("/category", methods=["GET", "POST"])
def index():
"""
Render form and handle form submission
"""
form = TestForm(request.form)
form.category_1.choices = [('', 'Select a Category')] + [(x) for x in enumerate(extra,1)]
chosen_category_1 = None
chosen_category_2 = None
chosen_category_3 = None
return render_template('index.html', form=form)
@app.route("/category/<int:category_1_id>/", methods=["POST"])
def get_request(category_1_id):
data = [(x) for x in enumerate(extra,1)
if x[0] != category_1_id]
response = make_response(json.dumps(data))
response.content_type = 'application/json'
return response
if __name__ == "__main__":
app.run(debug=True)
JS
$(function() {
// test to ensure jQuery is working
console.log("whee!")
// disable refresh button
$("#refresh-btn").prop("disabled", true)
$("#category_1_select").change(function() {
// grab value
var category_1_id = $("#category_1_select").val();
var category_2_id = $("#category_2_select").val();
// send value via GET to URL /<category_id>
var get_request = $.ajax({
type: 'POST',
url: '/category/' + category_1_id + '/',
});
// handle response
get_request.done(function(data){
// data
console.log(data)
// add values to list
var option_list = [["", "Select another category"]].concat(data);
$("#employee_select").empty();
for (var i = 0; i < option_list.length; i++) {
$("#employee_select").append(
$("<option></option>").attr("value", option_list[i][0]).text(option_list[i][1]));
}
// show model list
$("#employee_select").show();
});
});
$("#employee_select").change(function() {
// grab value
var category_1_id = $("#category_1_select").val();
var category_2_id = $("#category_2_select").val();
// send value via GET to URL /<category_id>
var get_request = $.ajax({
type: 'POST',
data: 'JSON.stringify([category_1_id, category_2_id])',
url: '/category/' + category_1_id + '/',
});
// handle response
get_request.done(function(data){
// data
console.log(data)
// add values to list
var option_list = [["", "Select another category"]].concat(data);
$("#category_3_select").empty();
for (var i = 0; i < option_list.length; i++) {
$("#category_3_select").append(
$("<option></option>").attr("value", option_list[i][0]).text(option_list[i][1]));
}
// show model list
$("#category_3_select").show();
});
});