Appearance
9.2 表单提交 method="get" / "post"
表单是用户与网站交互的重要方式,通过设置 method 属性可以指定表单数据的提交方式。
基本语法
html
<form action="处理文件.php" method="get|post">
<!-- 表单元素 -->
</form>method 属性值
method="get"
- 数据通过 URL 传递
- 数据会显示在地址栏中
- 适合传递少量非敏感数据
- 常用于搜索、筛选等操作
method="post"
- 数据通过 HTTP 请求体传递
- 数据不会显示在地址栏中
- 适合传递大量数据或敏感信息
- 常用于登录、注册、表单提交等操作
示例代码
GET 方法提交表单
html
<!DOCTYPE html>
<html>
<head>
<title>GET 方法示例</title>
</head>
<body>
<h2>搜索表单(GET 方法)</h2>
<form action="search.php" method="get">
<label>关键词: <input type="text" name="keyword"></label><br>
<label>分类:
<select name="category">
<option value="all">全部</option>
<option value="news">新闻</option>
<option value="products">产品</option>
<option value="articles">文章</option>
</select>
</label><br>
<input type="submit" value="搜索">
</form>
</body>
</html>POST 方法提交表单
html
<!DOCTYPE html>
<html>
<head>
<title>POST 方法示例</title>
</head>
<body>
<h2>注册表单(POST 方法)</h2>
<form action="register.php" method="post">
<label>用户名: <input type="text" name="username"></label><br>
<label>密码: <input type="password" name="password"></label><br>
<label>邮箱: <input type="email" name="email"></label><br>
<label>性别:
<input type="radio" name="gender" value="male"> 男
<input type="radio" name="gender" value="female"> 女
</label><br>
<label>爱好:
<input type="checkbox" name="hobbies[]" value="reading"> 阅读
<input type="checkbox" name="hobbies[]" value="sports"> 运动
<input type="checkbox" name="hobbies[]" value="music"> 音乐
</label><br>
<input type="submit" value="注册">
</form>
</body>
</html>服务器端处理代码
php
<?php
// search.php(处理 GET 请求)
if (isset($_GET['keyword'])) {
$keyword = $_GET['keyword'];
$category = isset($_GET['category']) ? $_GET['category'] : 'all';
echo "搜索关键词: $keyword<br>";
echo "分类: $category<br>";
echo "URL: " . $_SERVER['REQUEST_URI'] . "<br>";
}
// register.php(处理 POST 请求)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$hobbies = isset($_POST['hobbies']) ? $_POST['hobbies'] : [];
echo "用户名: $username<br>";
echo "邮箱: $email<br>";
echo "性别: $gender<br>";
echo "爱好: " . implode(', ', $hobbies) . "<br>";
echo "数据通过 POST 方法提交<br>";
}
?>注意事项
- 安全性:对于包含敏感信息的表单(如登录、注册),应使用 POST 方法
- 数据量:对于大量数据的提交,应使用 POST 方法
- 字符编码:确保表单使用正确的字符编码(通常为 UTF-8)
- 表单验证:无论使用哪种方法,都应该在服务器端进行表单验证
- CSRF 防护:对于 POST 表单,应考虑添加 CSRF 令牌以提高安全性
练习
- 创建一个使用 GET 方法的搜索表单
- 创建一个使用 POST 方法的登录表单
- 实现服务器端的表单处理代码
