htmx发出ajax请求后如何执行javascript代码?

com*_*ser 7 django htmx

我目前正在使用 django 和 htmx 构建一个网站,到目前为止我很喜欢这个组合。假设我在按钮上使用 htmx 属性,将 DOM 中的一个 div 替换为另一个应该包含所见即所得编辑器的 div。现在必须使用 javascript 初始化所见即所得编辑器。我该怎么做呢?我可以只返回 htmx 请求的编辑器 div 下的脚本标签吗?这不是有点丑陋或不好的做法吗,因为你在 html 正文的中间有脚本标签?解决这个问题的最好方法是什么?提前致谢

Kin*_*Man 13

简答

要在 HTMX 请求后运行特定代码,您需要监听该htmx:afterRequest事件。

htmx:afterRequest无论您尝试侦听的只是一个事件(还是您有应在所有htmx 请求之后运行的代码),您都可以使用以下事件侦听器在任何 HTMX 请求完成后运行您的代码:

document.addEventListener('htmx:afterRequest', function(evt) {
    // Put the JS code that you want to execute here
});
Run Code Online (Sandbox Code Playgroud)

长答案

如果您希望它仅在特定事件之后运行,则需要访问与该事件关联的对象,您应该完整evt参考此处的官方文档。不过,我在下面举了一些简单的例子来演示它的样子。

document.addEventListener('htmx:afterRequest', function(evt) {
    if(evt.detail.xhr.status == 404){
        /* Notify the user of a 404 Not Found response */
        return alert("Error: Could Not Find Resource");
    } 
    if (evt.detail.successful != true) {
        /* Notify of an unexpected error, & print error to console */
        alert("Unexpected Error");
        return console.error(evt);
    }
    if (evt.detail.target.id == 'info-div') {
        /* Execute code on the target of the HTMX request, which will
        be either the hx-target attribute if set, or the triggering 
        element itself if not set. */
        let infoDiv = document.getElementById('info-div');
        infoDiv.style.backgroundColor = '#000000';  // black background
        infoDiv.style.color = '#FFFFFF';  // white text
    }
});
Run Code Online (Sandbox Code Playgroud)

有关您可以侦听的 HTMX 事件的完整列表(例如,htmx:configRequest 在发送之前修改 HTMX AJAX 请求),请查看此处的官方参考。

至于将其放在代码中的何处的问题,唯一的技术必要性是在事件触发之前监听该事件:即不要在响应中发送此代码,而是预先将其放在您的页面中。那么在风格上放在哪里本质上是一个偏好问题。在 Django + HTMX 堆栈中,将其作为script标签包含在模板本身中,或者将其放入静态 js 文件中并链接到它是完全有效的。只需确保在执行之前加载 HTMX 库,并且您已csrf适当地解决了问题。

  • 另外,最好使用“htmx:afterSettle”事件。在 `htmx:afterRequest` 和 `htmx:afterSwap` 的情况下,我发现 JS 代码运行时 DOM 没有被完全替换。使用“htmx:afterSettle”,替换似乎可靠:-) (2认同)

小智 5

请求事件后查看 HTMX。

它应该看起来像这样

htmx.on('htmx:afterRequest', (evt) => {
  // check which element triggered the htmx request. If it's the one you want call the function you need
//you have to add htmx: before the event ex: 'htmx:afterRequest'
})
Run Code Online (Sandbox Code Playgroud)