在 HTML 中,action是<form>(表单)元素的一个属性,用于指定表单提交时数据发送的目标 URL。
基本语法
<form action="目标地址" method="请求方法"> <!-- 表单内容 --> </form>作用说明
- 当用户点击提交按钮(如
<input type="submit">或<button type="submit">)时,浏览器会将表单数据发送到action属性指定的 URL。 - 若未设置
action,默认提交到当前页面 URL(即刷新当前页)。
示例
1. 提交到服务器接口
<form action="/submit-form" method="POST"> <input type="text" name="username" placeholder="用户名"> <input type="password" name="password" placeholder="密码"> <button type="submit">登录</button> </form>用户点击“登录”后,数据会被 POST 请求发送到
/submit-form。
2. 使用完整 URL(跨域提交)
<form action="https://api.example.com/register" method="POST"> <input type="email" name="email" required> <button type="submit">注册</button> </form>3. 不设置action(默认行为)
<form method="GET"> <input type="text" name="search"> <button type="submit">搜索</button> </form>表单提交时会刷新当前页面,并将数据附加到 URL 查询参数中(如
?search=关键词)。
配合属性
method:指定 HTTP 请求方式(GET或POST)。enctype:指定表单数据编码方式(如上传文件时用multipart/form-data)。
与 JavaScript 结合
即使使用 JavaScript 处理表单(如 AJAX),保留action有助于语义化和降级兼容(即 JS 失效时仍可提交):
<form action="/backup-submit" method="POST" onsubmit="handleSubmit(event)"> <input type="text" name="message"> <button type="submit">发送</button> </form>总结
| 属性 | 作用 | 默认值 |
|---|---|---|
action | 表单提交的目标 URL | 当前页面 URL |
method | 请求方式(GET/POST) | GET |
enctype | 数据编码格式 | application/x-www-form-urlencoded |
✅核心理解:action告诉浏览器:“把数据送到哪儿去”。