在 HTML 页面里,我们需要编写表单来获取用户输入。一个典型的表单如下所示:
<form method="post"> <!-- 指定提交方法为 POST -->
<label for="name">名字</label>
<input type="text" name="name" id="name"><br> <!-- 文本输入框 -->
<label for="occupation">职业</label>
<input type="text" name="occupation" id="occupation"><br> <!-- 文本输入框 -->
<input type="submit" name="submit" value="登录"> <!-- 提交按钮 -->
</form>
编写表单的 HTML 代码有下面几点需要注意:
- 在
<form>
标签里使用method
属性将提交表单数据的 HTTP 请求方法指定为 POST。如果不指定,则会默认使用 GET 方法,这会将表单数据通过 URL 提交,容易导致数据泄露,而且不适用于包含大量数据的情况。 <input>
元素必须要指定name
属性,否则无法提交数据,在服务器端,我们也需要通过这个name
属性值来获取对应字段的数据。
提示 填写输入框标签文字的 <label>
元素不是必须的,只是为了辅助鼠标用户。当使用鼠标点击标签文字时,会自动激活对应的输入框,这对复选框来说比较有用。for
属性填入要绑定的 <input>
元素的 id
属性值。
创建新条目
创建新条目可以放到一个新的页面来实现,也可以直接在主页实现。这里我们采用后者,首先在主页模板里添加一个表单:
templates/index.html:添加创建新条目表单
<p>{
{ movies|length }} Titles</p>
<form method="post">
Name <input type="text" name="title" autocomplete="off" required>
Year <input type="text" name="year" autocomplete="off" required>
<input class="btn" type="submit" name="submit" value="Add">
</form>
在这两个输入字段中,autocomplete
属性设为 off
来关闭自动完成(按下输入框不显示历史输入记录);另外还添加了 required
标志属性,如果用户没有输入内容就按下了提交按钮,浏览器会显示错误提示。
两个输入框和提交按钮相关的 CSS 定义如下:
/* 覆盖某些浏览器对 input 元素定义的字体 */
input[type=submit] {
font-family: inherit;
}
input[type=text] {
border: 1px solid #ddd;
}
input[name=year] {
width: 50px;
}
.btn {
font-size: 12px;
padding: 3px 5px;
text-decoration: none;
cursor: pointer;
background-color: white;
color: black;
border: 1px solid #555555;
border-radius: 5px;
}
.btn:hover {
text-decoration: none;
background-color: black;
color: white;
border: 1px solid black;
}
接下来,我们需要考虑如何获取提交的表单数据。
处理表单数据
默认情况下,当表单中的提交按钮被按下,浏览器会创建一个新的请求,默认发往当前 URL(在 <form>
元素使用 action
属性可以自定义目标 URL