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


How do I create an auto suggestion from a JSON API response?

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

如果您可以使用jqueryui-autocomplete插件,那么您可以将其源选项设置为一个函数,该函数介于jqueryui-autocomplete所需的格式和亚马逊提供的API之间。以下内容应该能够处理基于您作为示例给出的JSON的JSONP响应。您可以看到,您提供的API端点通过向示例URI添加callback GET参数来支持JSONP。例如http://completion.amazon.com/search/complete?search-别名=aps&client=亚马逊搜索ui&mkt=1&q=facebook&callback=_返回在对_()的调用中封装的数据。jQuery用它的dataType: 'jsonp'选项掩盖了这一点。这对于支持跨站点请求是必要的,因为您不太可能为您的站点提供与完成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(); });内部运行。