lpa*_*s12 4 django python-3.x alpine.js htmx
因此,当使用 HTMX 将表单提交到我的 Django 后端时,我尝试显示一条反馈消息,指出“已添加”或“失败”。
基本上我现在拥有的是一个执行 hx-post 的表单,回复是div
包含更新的信息,该信息与 .hx-post 的当前内容交换div
。
<div id="list">
<!-- The stuff in here is loaded through another template, which is
the result of a successful myApp:add operation. -->
</div>
<form hx-post="{% url 'myApp:add' eid=e.id %}" hx-swap="outerHTML" hx-target="#list">
<!-- Some stuff in here -->
</form>
<div id="result">
<!-- Here I should print a message saying correct or incorrect
depending on the HTMX result (if the entry was added or there was
any kind of error, even connection errors) -->
</div>
Run Code Online (Sandbox Code Playgroud)
问题是,如果表单或请求本身出现错误,列表将保持不变,但我希望它在 div 中打印类似“错误”的内容result
。如果正确添加新条目,我想在结果 div 中打印“成功”消息。
请注意,我无法将结果 div 作为 hx-post 响应 DOM 的一部分返回,因为连接可能会失败。所以不会显示失败消息。
我也在使用 Alpine.js,如果有帮助的话。
如果您可以在现有代码周围添加一个 div,那么这是使用 Alpine 执行此操作的一种方法:
<div x-data="{ state: '' }"
@htmx:send-error="state = 'send error'"
@htmx:response-error="state = 'response error'"
@htmx:after-swap="state = 'success'"
>
<div id="list"></div>
<form hx-post="{% url 'myApp:add' eid=e.id %}" hx-swap="outerHTML" hx-target="#list">
<button type="submit">Submit</button>
</form>
<div id="result">
<span x-text="state"></span>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
事件在目标上触发#list
,因此它们会冒泡到父 div。如果您希望将 Alpine 组件添加到 div,#result
您可以通过监听窗口上的事件来完成:
<div id="result" x-data="{ state: '' }"
@htmx:send-error.window="state = 'send error'"
@htmx:response-error.window="state = 'response error'"
@htmx:after-swap.window="state = 'success'">
<span x-text="state"></span>
</div>
Run Code Online (Sandbox Code Playgroud)
如果您使用第二种方法,并且同一页面上发生多个 htmx 请求,您还可以读取$event.detail.target.id
Alpine 事件中的值以添加一些逻辑。在上述情况下,该值应为list
。
要处理来自服务器的特定响应代码,您可以检查$event.detail.xhr.status
事件中的值。例如:
<div id="result" x-data="{ state: '' }"
@htmx:send-error.window="state = 'send error'"
@htmx:response-error.window="state = $event.detail.xhr.status == 400 ? 'validation error' : 'response error'"
@htmx:after-swap.window="state = 'success'">
<span x-text="state"></span>
</div>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2170 次 |
最近记录: |