透過 Python 將多選框資料傳遞至 CGI 程式


在需要選擇多個選項時,會使用多選框。

示例

以下是包含兩個多選框的表單的 HTML 程式碼示例 −

<form action = "/cgi-bin/checkbox.cgi" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" value = "on" /> Maths
<input type = "checkbox" name = "physics" value = "on" /> Physics
<input type = "submit" value = "Select Subject" />
</form>

輸出

此程式碼的結果為以下表單 −

以下是用來處理網頁瀏覽器給予的多選框按鈕輸入的 checkbox.cgi 指令碼。

#!/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('maths'):
   math_flag = "ON"
else:
   math_flag = "OFF"
if form.getvalue('physics'):
   physics_flag = "ON"
else:
   physics_flag = "OFF"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Maths is : %s</h2>" % math_flag
print "<h2> CheckBox Physics is : %s</h2>" % physics_flag
print "</body>"
print "</html>"

更新於: 31-Jan-2020

458 次瀏覽

啟動您的 事業

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.