如何将复选框数据传给 Python CGI 脚本?\n\n


将复选框数据传递给 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>

此代码的输出为以下表单 −

Maths  Physics Select Subject

以下是处理 Web 浏览器为复选框按钮提供的输入的 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>"

更新于: 16-Jun-2020

435 次浏览

启动你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.