主动搜索

此示例在用户输入文本时主动搜索联系人数据库。

我们从一个搜索输入框和一个空表格开始:

<h3>
  Search Contacts
  <span class="htmx-indicator">
    <img src="/img/bars.svg"/> Searching...
   </span>
</h3>
<input class="form-control" type="search"
       name="search" placeholder="Begin Typing To Search Users..."
       hx-post="/search"
       hx-trigger="input changed delay:500ms, keyup[key=='Enter'], load"
       hx-target="#search-results"
       hx-indicator=".htmx-indicator">

<table class="table">
    <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
    </tr>
    </thead>
    <tbody id="search-results">
    </tbody>
</table>

输入框在 input 事件上向 /search 发出 POST 请求,并将表格主体设置为结果内容。

我们向触发器添加 delay:500ms 修饰符,以延迟发送查询,直到用户停止输入。此外,我们向触发器添加 changed 修饰符,以确保当用户不更改输入值时不发送新查询(例如,他们按下箭头键,或粘贴相同的值)。

我们可以通过逗号分隔来使用多个触发器,这样我们添加了另外 2 个触发器:

最后,我们使用 hx-indicator 属性在搜索进行中显示一个指示器。

Server Requests ↑ Show

🔗Demo