9

我们正在使用 google 自定义搜索 API(付费的服务器端 API)来支持我们的搜索结果。

我想在搜索中添加一个自动完成功能 - 但是,有谁知道是否支持此功能(通过服务器端 API,或者通过某种客户端 JSONP?)

我曾尝试使用 Google 自定义搜索的自动完成功能,但这似乎想要绘制搜索框并显示带有结果的 google 广告,这是我不想要的。

4

2 回答 2

13

得到这样的工作 - 希望这对其他人有帮助:)

$(function () {
  $('input.search')
    .focus(function () { this.select(); })
    .mouseup(function (e) { e.preventDefault(); })
    .autocomplete({
      position: {
        my: "left top",
        at: "left bottom",
        offset: "0, 5",
        collision: "none"
      },
      source: function (request, response) {
        $.ajax({
          url: "http://clients1.google.com/complete/search?q=" + request.term + "&hl=en&client=partner&source=gcsc&partnerid={GOOGLESEARCHID}&ds=cse&nocache=" + Math.random().toString(),
          dataType: "jsonp",
          success: function (data) {
            response($.map(data[1], function (item) {
              return {
                label: item[0],
                value: item[0]
              };
            }));
          }
        });
      },
      autoFill: true,
      minChars: 0,
      select: function (event, ui) {
        $(this).closest('input').val(ui.item.value);
        $(this).closest('form').trigger('submit');
      }
    });
});
于 2011-11-29T15:12:41.673 回答
1

在撰写本文时(2013 年 6 月),有一种更简单的方法来获取自动完成功能,同时仍以 XML 格式获取结果:

<gcse:searchbox-only enableAutoComplete="true" resultsUrl="#"></gcse:searchbox-only>

  • “诀窍”是您可以指定“resultsUrl”,这意味着您可以将实际搜索结果定向到您通过 XML API 生成的页面,而无需自己实现搜索框 UX。
于 2013-06-26T23:22:39.280 回答