HTML form 参考
<form> 用于组织用户输入,并把字段提交给服务端或交给 JavaScript 处理。现代前端项目中,表单经常配合 FormData、fetch 和浏览器内置校验使用。
语法
<form action="/api/contact" method="post">
<label>
邮箱
<input name="email" type="email" required>
</label>
<button type="submit">提交</button>
</form>
常用属性
| 属性 | 说明 |
|---|---|
action |
表单提交地址 |
method |
提交方法,常见为 get 或 post |
enctype |
请求体编码,文件上传常用 multipart/form-data |
target |
提交后打开位置 |
novalidate |
禁用浏览器内置校验 |
可运行演示
源码
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>form 表单演示</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; padding: 24px; font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #0f172a; background: #f8fafc; }
form { max-width: 680px; margin: 0 auto; padding: 20px; border: 1px solid #dbeafe; border-radius: 12px; background: #fff; }
label { display: grid; gap: 6px; margin-bottom: 14px; font-weight: 600; }
input, textarea { padding: 10px; border: 1px solid #cbd5e1; border-radius: 8px; font: inherit; }
textarea { min-height: 100px; resize: vertical; }
button { padding: 10px 14px; border: 0; border-radius: 8px; color: #fff; background: #2563eb; cursor: pointer; }
output { display: block; margin-top: 12px; color: #475569; }
</style>
</head>
<body>
<form id="contact">
<label>邮箱 <input name="email" type="email" required placeholder="[email protected]"></label>
<label>留言 <textarea name="message" required>你好,菜鸟教程。</textarea></label>
<button type="submit">提交</button>
<output id="result">提交时会用 FormData 读取字段。</output>
</form>
<script>
document.querySelector("#contact").addEventListener("submit", (event) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(event.currentTarget));
document.querySelector("#result").textContent = JSON.stringify(data);
});
</script>
</body>
</html>
常见错误
- 按钮没有写
type,默认submit,可能意外提交表单。 - 表单控件缺少
name,提交或创建FormData时拿不到字段。 - 文件上传时忘记使用
FormData,或者手动设置错误的Content-Type。 - 只靠前端校验,服务端没有再次校验输入。
相关内容
相关内容
- canonical 参考 canonical Reference,整理 rel=canonical 的写法、规范 URL、重复页面处理、SEO 注意事项和常见错误。
- HTML img 参考 HTML img Reference,整理 src、alt、width、height、loading、decoding、srcset、sizes、可访问性和常见...
- HTML input 参考 HTML input Reference,整理 type、name、value、placeholder、required、autocomplete、常见输入类型...
- HTML meta 参考 HTML meta Reference,整理 charset、viewport、description、robots、theme-color、Open Grap...
- HTML picture 参考 HTML picture Reference,整理 source、media、type、srcset、响应式图片、可运行演示和常见错误。