You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript修改HTMX的hx-get属性后结果未更新问题求助

问题:HTMX表单提交后始终返回初始参数结果

我正在开发一个基于FastAPI、HTMX、Tailwind和MongoDB的简单应用,遇到了HTMX相关问题。当我选择下拉框中的货币时,HTML里的hx-get属性确实发生了变化,但提交表单后始终返回EUR对应的数据结果。

我的表单代码:

<form id="currencyForm" hx-get="/currency_history_check/EUR" hx-target="#result" hx-swap="innerHTML">
  <select name="currency_id" id="currency_id" onchange="updateFormAction()">
  </select>
  <button type="submit">Submit</button>
</form>
<div id="result">

</div>

对应的脚本:

function updateFormAction() {
        var selectedCurrency = document.getElementById("currency_id").value;
        document.getElementById("currencyForm").setAttribute("hx-get", "/currency_history_check/" + selectedCurrency);
    }

问题原因

HTMX在初始化表单时会缓存初始的请求URL,后续通过原生JS修改hx-get属性后,HTMX内部并没有同步更新这个缓存的URL,所以提交时依然使用初始的/currency_history_check/EUR。

解决方法

方法1:强制HTMX重新处理表单

修改JS函数,在修改hx-get属性后调用htmx.process()让HTMX重新解析表单,更新内部缓存:

function updateFormAction() {
    const selectedCurrency = document.getElementById("currency_id").value;
    const form = document.getElementById("currencyForm");
    form.setAttribute("hx-get", "/currency_history_check/" + selectedCurrency);
    htmx.process(form); // 关键:让HTMX重新处理表单
}

方法2:改用查询参数传递(更简洁)

放弃修改URL路径,直接通过表单参数传递货币ID,符合HTMX原生表单提交逻辑:

  1. 修改HTML表单的hx-get为固定路径:
<form id="currencyForm" hx-get="/currency_history_check" hx-target="#result" hx-swap="innerHTML">
  <select name="currency_id" id="currency_id">
  </select>
  <button type="submit">Submit</button>
</form>
  1. FastAPI接口改为接收查询参数:
@app.get("/currency_history_check")
async def get_currency_history(currency_id: str):
    # 这里使用currency_id参数处理业务逻辑
    ...

这种方式不需要额外的JS函数,HTMX会自动将表单的currency_id值作为查询参数发送给后端。


内容的提问来源于stack exchange,提问作者AdrianIT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 16:52:16