3

亚马逊提供了一个 API 来获取输入字母的建议:

 http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q=facebook

会给出回应:

["facebook",["facebook","facebook login","facebook.com","facebook credits","facebook gift card","facebook app","facebook messenger","facebook for dummies","facebook en español","facebook phone"],[{"nodes":[{"alias":"mobile-apps","name":"Apps for Android"},{"alias":"stripbooks","name":"Books"},{"alias":"textbooks-tradein","name":"Books Trade-in"},{"alias":"digital-text","name":"Kindle Store"}]},{},{},{},{},{},{},{},{},{}],[]]

如何使用 jQuery 或 PHP 从这个 JSON 响应创建自动建议?

4

1 回答 1

5

如果您可以使用jqueryui-autocomplete插件,那么您可以将其选项设置为 aa 函数,该函数在 jqueryui-autocomplete 需要的格式和 Amazon 提供的 API 之间进行调解。以下应该能够根据您作为示例提供的 JSON 处理 JSONP 响应。callback通过向示例 URI添加 GET 参数,您可以看到您提供的 API 端点支持 JSONP 。例如,http://completion.amazon.com/search/complete ?search-alias=aps&client=amazon-search-ui&mkt=1&q=facebook&callback=_返回包装在对_(). dataType: 'jsonp'jQuery 用它的选项掩盖了这一点。这对于支持跨站点请求是必要的,因为您不太可能使用来源与完成 API 的来源相同。

/*
 * Connect all <input class="autocomplete"/> to Amazon completion.
 */
jQuery('input.autocomplete').autocomplete({
  source: function(request, response) {
    jQuery.ajax('http://completion.amazon.com/search/complete', {
      /* Disable cache breaker; potentially improves performance. */
      cache: true,
      data: {
        client: 'amazon-search-ui',
        mkt: 1,
        'search-alias': 'aps',
        q: request.term
      },
      error: function() {
        /*
         * jquery-autocomplete’s documentation states that response()
         * must be called once per autocomplete attempt, regardless
         * of whether or not the background request completed
         * successfully or not.
         */
        response([]);
      },
      success: function(data) {
        /*
         * Amazon returns an array of different types of
         * autocomplete metadata. The second member is a
         * list of terms the user might be trying to type.
         * This list is compatible with jqueryui-autocomplete.
         */
        response(data[1]);
      },
      dataType: 'jsonp'
    });
  }
});

请记住在 DOM 准备好后运行此代码,例如从jQuery(document).ready(function() { statements_here(); });.

于 2013-07-02T06:20:15.080 回答