如何让htmx 2.0.4像1.8.0一样通过表单数据发送选中值?
摘要
- htmx 1.8.0 通过表单数据(form data)发送DELETE请求的表单数据
- htmx 2.0.4 通过URL参数发送DELETE请求的表单数据
示例
以下是简化的示例代码:
<!doctype html> <html lang=""> <head> <script src="/static/js/htmx-1.8.0.js"></script> {# <script src="https://unpkg.com/htmx.org@2.0.4/dist/htmx.min.js"></script> #} </head> <body> <main> <form x-data="{ selected: [] }"> <table> <thead> <tr> <th></th> <th>First</th> <th>Last</th> <th>Phone</th> <th>Email</th> <th></th> </tr> </thead> <tbody> {% for contact in contacts %} <tr> <td><input type="checkbox" name="selected_contact_ids" value="{{ contact.id }}" x-model="selected"></td> <td>{{ contact.first }}</td> <td>{{ contact.last }}</td> <td>{{ contact.phone }}</td> <td>{{ contact.email }}</td> <td></td> </tr> {% endfor %} </tbody> </table> <button hx-delete="/contacts" hx-confirm="Confirm deletion" hx-target="body"> Delete Selected Contacts </button> </form> </main> </body> </html>
选中部分联系人后:
- 使用htmx 1.8.0时,点击删除按钮,开发者工具显示选中的联系人ID通过表单数据(form data)发送;
- 替换为htmx 2.0.4后,选中的值会通过URL参数发送。
问题
如何让htmx 2.0.4像1.8.0版本一样,通过表单数据发送选中的值?
解决方案
方式一:给按钮添加hx-encoding属性
直接在删除按钮上显式指定编码方式,强制htmx通过表单数据发送请求体:
<button hx-delete="/contacts" hx-confirm="Confirm deletion" hx-target="body" hx-encoding="application/x-www-form-urlencoded"> Delete Selected Contacts </button>
也可以使用multipart/form-data作为编码值,根据后端接收需求选择即可。
方式二:修改全局默认配置
如果希望所有DELETE请求都沿用1.x版本的行为,可通过全局配置调整:
htmx.config.defaultDeleteEncoding = 'application/x-www-form-urlencoded';
可以将这段代码放在htmx脚本加载之后,或者页面初始化事件中:
<script> document.addEventListener('DOMContentLoaded', function() { htmx.config.defaultDeleteEncoding = 'application/x-www-form-urlencoded'; }); </script>
说明
htmx 2.x版本对DELETE请求的默认行为做了调整,默认将表单数据拼接为URL参数发送,而1.x版本默认通过请求体的表单数据发送。通过上述两种方式,即可恢复旧版本的行为。
内容的提问来源于stack exchange,提问作者dharmatech
相关产品推荐
相关产品推荐

