使用FastHTML点击按钮更新div内容无响应问题排查
问题分析与解决
核心问题是生成的HTML中未引入HTMX脚本库——浏览器无法识别hx-get、hx-target这类HTMX专属属性,因此点击按钮不会发起请求,也无法更新页面内容。
修复方案
修改index函数,在HTML的<head>中添加HTMX的CDN脚本引用:
from fasthtml.common import * app = FastHTML() @app.route("/", methods=["get"]) def index(): return Html( Head( Script(src="https://unpkg.com/htmx.org@1.9.10") ), Body( Header(navigation_bar(["page1", "page2"])), Div(page1(), id="page-content"), ), ) def navigation_bar(navigation_items: list[str]): return Nav( Ul( *[ Li(Button(item, hx_get=f"/{item}", hx_target="#page-content")) for item in navigation_items ] ), ) @app.route("/page1", methods=["get"]) def page1(): return Div("You are on page 1.") @app.route("/page2", methods=["get"]) def page2(): return Div("You are on page 2.") serve()
添加脚本后,浏览器会加载HTMX库,此时按钮上的hx-get和hx-target属性会被正确解析:点击按钮时发起对应路由的GET请求,将返回内容替换到#page-content元素中。
内容的提问来源于stack exchange,提问作者vr_dz
相关产品推荐
相关产品推荐

