如何从JSON API响应创建自动建议?

时间:2013-07-02 04:03:21

标签: php ajax json jquery

亚马逊提供了一个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响应创建自动建议?

1 个答案:

答案 0 :(得分:5)

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

/*
 * 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(); });内部运行。