jQueryでAmazon/Googleのsuggest機能を実装する
AmazonやGoolgeなどのSuggest機能を実装する場合、jQuery-UIのautocompleteを使うと簡単にできる。
autocompleteは、jQuery-UI ver1.8から実装された機能。
基本的に、クエリを組み立てる部分だけ気を付ければよい。
Amazon以外でも、Google、YahooなどSuggest APIが公開されているサービスと、簡単に連携できる。
戻り値がXMLの場合は、プラグインなどを使って、オブジェクトの形式に変換した方がよい。
取得データがJSON(JSONP)でないと、クロスドメインに対応するのが面倒なので注意が必要。
Amazon Suggestの場合
- 外部サイトなので、データのタイプを「jsonp」にする必要がある。
- 戻り値はJSONだが、候補は配列の2番目の要素(インデックスは1)をレスポンスに設定する。
- クエリのパラメータ「search-alias」にはハイフン「-」があるため、文字列にしている。
<script src="/js/jquery.js" charset="UTF-8"></script> <script src="/js/jquery-ui.js" charset="UTF-8"></script> <link rel="stylesheet" type="text/css" href="/css/ui-lightness/jquery-ui-1.10.4.custom.min.css"> <script type="text/javascript"> $(document).ready(function(){ $('#keyword').autocomplete({ source: function(request, response){ $.ajax({ url: "http://completion.amazon.co.jp/search/complete", data: {mkt:'6', method:'completion', 'search-alias':'aps', q: request.term}, dataType: "jsonp", type: "GET", success :function(data) { response(data[1]); } }); }, delay: 300 }); }); </script> <input id="keyword" type="text" name="keyword">
補足
ジャンルで絞り込みたい場合は、「search-alias」を変更する。
基本的に、Pdoduct APIのパラメータ「SearchIndex」に似ているが、完全な対応とは違うので注意が必要。
aps=All Departments instant-video=Amazon Instant Video appliances=Appliances mobile-apps=Apps for Android arts-crafts=Arts, Crafts & Sewing automotive=Automotive baby-products=Baby beauty=Beauty stripbooks=Books mobile=Cell Phones & Accessories apparel=Clothing & Accessories collectibles=Collectibles computers=Computers electronics=Electronics gift-cards=Gift Cards Store grocery=Grocery & Gourmet Food hpc=Health & Personal Care garden=Home & Kitchen industrial=Industrial & Scientific jewelry=Jewelry digital-text=Kindle Store magazines=Magazine Subscriptions movies-tv=Movies & TV digital-music=MP3 Music popular=Music mi=Musical Instruments office-products=Office Products lawngarden=Patio, Lawn & Garden pets=Pet Supplies shoes=Shoes software=Software sporting=Sports & Outdoors tools=Tools & Home Improvement toys-and-games=Toys & Games videogames=Video Games watches=Watches
Google Suggestの場合
- Amazonの場合と同様外部サイトなので、データのタイプを「jsonp」にする必要がある。
- Google Suggestの場合、取得可能なデータ形式を指定する際に、「client=firefox」とするとJSON型が返ってくる。
- 「output=toolbar」と指定すると、XML形式が返ってくる。
<script type="text/javascript"> $(document).ready(function(){ $('#keyword').autocomplete({ source: function(request, response){ $.ajax({ url: "http://www.google.com/complete/search", data: {hl:'ja', client:'firefox', q: request.term}, dataType: "jsonp", type: "GET", success :function(data) { //alert(data); response(data[1]); } }); }, delay: 300 }); });