主动搜索

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

¥This example actively searches a contacts database as the user enters text.

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

¥We start with a search input and an empty table:

<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>名字</th>
      <th>姓氏</th> 
      <th>电子邮件</th>
    </tr>
    </thead>
    <tbody id="search-results">
    </tbody>
</table>


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

¥The input issues a POST to /search on the input event and sets the body of the table to be the resulting content.

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

¥We add the delay:500ms modifier to the trigger to delay sending the query until the user stops typing. Additionally, we add the changed modifier to the trigger to ensure we don’t send new queries when the user doesn’t change the value of the input (e.g. they hit an arrow key, or pasted the same value).

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

¥We can use multiple triggers by separating them with a comma, this way we add 2 more triggers:

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

¥Finally, we show an indicator when the search is in flight with the hx-indicator attribute.

Server Requests ↑ Show

🔗Demo