AJAXな画像検索を実装してみた
yahooAPIの画像検索を使い、テキストエリアに入力された語に関する画像を表示させるコードを書いてみました。
前提としてyahooAPIのIDが必要になります。
>| JS $("#search").keyup(function() { var searchword = $(this).attr("value"); //テキストエリアに入力されたワードを取得 $.get("/api/yahoo/", {word: searchword}, function(imgs){ var data = eval("(" + imgs + ")"); for (var i in data) { $("ul.imgs").append('<li><img src="'+data[i]+'" width=" 50" height="50" class="searchimg"/></li>'); } }); });
< |
テンプレート(ビュー) <input type="text" id="search" value=""/>検索用のテキストエリアです。
アクション public function executeIndex() { $word = $this->getRequestParameter("word"); $yahooimgs = $this->yahooimg($word); $json = new Services_JSON; echo $json->encode($yahooimgs); //JSONでJSに渡す exit; } private function yahooimg($word) { $host = "http://search.yahooapis.jp/ImageSearchService/V1/imageSearch"; $id = "?appid=hugahugahogehoge"; //yahooAPIのID $query = "&query={$word}"; //検索ワード $length = "&results=40"; //表示件数 $domain = "&site=www.google.co.jp"; //ドメイン検索(使ってません) $url = $host.$id.$query.$length; $datas = simplexml_load_file($url); $imgs = array(); $count = 1; foreach ($datas as $data) { $imgs[$count] = (string)$data->Thumbnail->Url; //画像検索のサムネイル画像を取得する $count++; } return $imgs; }symfony上でyahooAPIの画像検索を実装しています。 検索ワードに対してアイテムを40個取得し表示する。 大体こんな感じでyahooからリアルタイムに画像検索結果を取得できました。