Computer >> Máy Tính >  >> Lập trình >> Python

Chuyển dữ liệu hộp thả xuống cho chương trình CGI bằng Python

Hộp thả xuống được sử dụng khi chúng ta có nhiều tùy chọn nhưng chỉ một hoặc hai tùy chọn được chọn.

Ví dụ

Đây là mã HTML mẫu cho biểu mẫu có một hộp thả xuống -

<form action = "/cgi-bin/dropdown.py" method = "post" target = "_blank">
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
<input type = "submit" value = "Submit"/>
</form>

Đầu ra

Kết quả của mã này là dạng sau -

Chuyển dữ liệu hộp thả xuống cho chương trình CGI bằng Python

Dưới đây là tập lệnh dropdown.py để xử lý đầu vào do trình duyệt web cung cấp.

#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('dropdown'):
   subject = form.getvalue('dropdown')
else:
   subject = "Not entered"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Dropdown Box - Sixth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"