0

Python で書かれた cgi スクリプトがあります。2 つのドロップダウン メニューと送信ボタンがあります。最初のメニューから選択し、その選択に基づいて、2 番目のドロップダウン メニューに新しい選択肢を動的に入力できるようにしたいと考えています。2 番目のメニューは、ボタンをクリックする必要はなく、最初のメニューから選択するだけで表示されます。また、最初のメニューで新しい項目を選択するたびに、2 番目のメニューも継続的に再表示されるはずです。

これを実現するための一般的な考え方は何ですか? 私はすでにいくつかのコードを実装しています。入力が提供されているかどうかの条件で if/else ステートメントを使用します。そのため、最初のドロップダウン メニューの選択が行われた後、ページが送信され、if/else ステートメントが同じフォームを表示するコードに指示しますが、選択はドロップダウン メニューで維持されます。私は onchange='this.form.submit() を使用して、送信ボタンを使用せずにフォームを送信しています。現在の問題は、選択を行うと最初にフォームが自動的に送信されますが、このフォームでの再選択が機能しないように見えることです。したがって、 onchange='this.form.submit() が初めてフォームを送信するかどうかはわかりません。

これがプロトタイプです。私は正しい方向に進んでいますか?それとも、Ajax を使用する必要がありますか? (これにはまだまったく慣れていません):

firstChoicesList = firstChoices()
print(""" <form method="post" action="/cgi-bin/thisScript.py">""")

# if both choices are not selected yet
if "firstChoice" not in form and "secondChoice" not in form:
    # first choice drop down menu
    print("""<p>first choice <select name="firstChoice">""")
    for f in fristChoicesList:
        print("""<option value='""" + f + """'>""" + f + """</option>""")

    # second choice drop down menu
    print("""</select></p>""")
    print("""<p>second choice <select name="secondChoice">""")
    for f in secondChoicesList: # currently contains 1 empty string 
        print("""<option value='""" + f + """'>""" + f + """</option>""")
    print("""</select></p>""")
    print("""
                        <p><input type="submit" />
                </form>
    """)
    print("Please fill in the forms.")
    sys.exit(1) # don't proceed with rest of code below these if/else statements

# if first choice has been selected but not the second
elif "firstChoice" in form and "secondChoice" not in form: 
    # <code for first drop down menu again with choice selected>
    # this function takes the first choice as an argument and returns selections for the second menu
    secondChoicesList = secondChoices(form["firstChoice"].value) 
    # <code for second drop down menu with choices populated from secondChoicesList>
    print("""
                        <p><input type="submit" />
                </form>
    """)
    print("Please fill in the forms.")
    sys.exit(1)

# if both are selected 
else:
    # <same code as above except have both drop down menus save previous selections>
    # proceed to run rest of cgi script 
4

1 に答える 1