This article demonstrates how to use Flex 4 AutoComplete with Google Search Suggest.
First I use the Google Suggest API to show search suggestions in the AutoComplete as the user types in the input. Then I use the Google Search API to perform a Google search with the selected phrase.
Let’s see first how the finished application works – View source is enabled:
When user starts to type into search input we use an HttpService to get search suggestions from Google.
You can notice in the code sample below that the direct url is commented out. This is because the lack of a crossdomain.xml on Google’s servers prevent Flash from calling this url. So we call a php script instead in our domain that will load the data from Google and sends it back to Flash.
You can call the direct url in a browser to see the structure of the xml result. The result is an xml list that we feed into the dataprovider of the AutoComplete.
<components:AutoComplete id="autoC" change="onChange()" labelFunction="labelFunction" select="search()" enter="search()" width="200" /> <s:HTTPService id="googleSuggest" result="onResult(event)" showBusyCursor="true" resultFormat="e4x" /> private function onChange(){ var s = autoC.text; //googleSuggest.url = "http://google.com/complete/search?output=toolbar&q=" + s; googleSuggest.url = "../data/googlesuggest.php?q=" + s; googleSuggest.send(); } private function onResult(event:ResultEvent){ var xmlList:XMLList = googleSuggest.lastResult.CompleteSuggestion as XMLList autoC.dataProvider = new XMLListCollection(xmlList); }
We use another HttpService to call Google Search – this time the result format is a JSON string.
No proxy is needed because this service has a crossdomain.xml in place and accepts Flash calls.
The process is simple: when user presses enter or selects a suggestion in the AutoComplete we send the text to Google.
The result is then converted from JSON into Actionscript and displayed in a datagroup.
<s:HTTPService id="googleSearch" result="onSearchResult(event)" showBusyCursor="true" resultFormat="text" /> private function search(){ var s = autoC.text googleSearch.url = 'http://ajax.googleapis.com/ajax/services/search/web'; googleSearch.request.v = '1.0'; googleSearch.request.q = s; googleSearch.send(); } private function onSearchResult(event:ResultEvent){ var result:Object = JSON.decode(event.result as String).responseData.results; searchResults.dataProvider = new ArrayList(result as Array); }
Leave a comment: