# 预测搜索

> 为 Shoplazza 主题添加预测搜索，让商品建议在客户输入时即时出现，用到搜索 Ajax 接口与 search 对象。

您可以为 theme 添加预测搜索功能，使建议结果在您输入搜索词时立即显示。预测搜索帮助顾客明确和细化搜索查询，为他们提供探索在线店铺的新方式，并让他们无需离开当前页面查看独立的搜索结果列表即可快速浏览匹配内容。

预测搜索支持商品建议。

## 资源

* [预测搜索 API](./) 的 `/{locale}/api/search` endpoint
* [search object](/docs/theme/references/liquid/objects/search)
* [add\_root\_url filter](/docs/theme/references/liquid/filters/hosted-file#add_root_url)
* [spz-list 组件](https://lessjs.shoplazza.com/latest/components/spz-list/)

## 实现预测搜索

要支持预测搜索，您需要实现以下组件：

* 一个搜索输入框，供预测搜索应用。
* 一个 section，用于托管通用预测搜索展示界面。该展示界面使用 `spz-list component` 与 `/api/search` API 获取预测搜索结果并填充内容。

:::note
`spz-list` 组件目前仅在 `Geek`、`Flash`、`Wind`、`Nova 2023` 和 `One page` theme 中可用，其他 theme 需要使用 JavaScript 函数来展示搜索结果列表。
:::

```liquid title="snippets/search_predictive.liquid"
<input type="text" name="q" value="{{ search.terms | escape }}" @input-debounced="search-predictive-list.refresh(keyword=event.value)">

<spz-list
  id="search-predictive-list"
  layout="container"
  initial-page="0"
  size="limit"
  page-size="4"
  src="{{ '/api/search' | add_root_url }}?keyword={{ search.terms | escape}}"
  list="data.products"
  total="data.total"
>
  <template>
    <a href="${data.url}">
      <spz-img
        layout="responsive"
        width="${data.image.width}"
        height="${data.image.height}"
        src="${data.image.src}"
        alt="${data.image.alt}"
      ></spz-img>
      <span>${data.title}</span>
    </a>
  </template>
</spz-list>
```
