我有一个用 Python 编写的 cgi 脚本。有两个下拉菜单,然后是一个提交按钮。我希望能够从第一个菜单中进行选择,并根据该选择,让第二个下拉菜单动态填充新选择。第二个菜单应该无需单击任何按钮即可填充,而只需从第一个菜单中进行选择即可。每次我在第一个菜单上选择一个新项目时,第二个菜单也应该不断重新填充 - 再次,无需单击提交。
完成这项工作的总体思路是什么?我已经实现了一些代码。它根据是否提供输入的条件使用 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