Curl Global Community

Full Version: Google サジェストから候補データを取得し、オートコンプリートを作る
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Google サジェストから候補データを取得し、オートコンプリート機能を作るサンプルです。

以下のようにhttp://suggestqueries.google.comにリクエストを投げれば、JSONが返ってくるので、それを解析するだけでOK。

Code:
{define-proc {find-google-suggestions
                 word:String,
                 host-locale:Locale = {get-host-locale}
             }:{Array-of String}
    def query =
        "http://suggestqueries.google.com/complete/search?hl=%s&qu=%s&json=t"
    def suggestions = {{Array-of String}}
    def qu = {url-encode-string word}
    {with-open-streams
        tis = {read-open {url {format query, host-locale.name, qu}}}
     do
        def results = {JsonValue-parse tis} asa JsonArray
        {for v in results[1] asa JsonArray do
            {suggestions.append v asa String}
        }
    }
    {return suggestions}
}

{define-class public open GoogleSuggestionProvider
  {inherits AutocompleteProvider}

  {method public open {refresh acf:AutocompleteMixin}:void
    def word = acf.text-field.value
    {if word.size > 0 then
        {acf.populate-from-strings
            {find-google-suggestions word}
        }
    }
  }

  {constructor public {default max-results:int = 10}
    {construct-super max-results}
  }
}

{value
    {AutocompleteTextField
        height = 1cm,
        width = 10cm,
        font-size = 14px,
        {GoogleSuggestionProvider},
        {on FocusIn at acf:AutocompleteTextField do
            {acf.provider.refresh acf}
        }
    }
}

この中では、Curl External LibraryのAutoCompleteTextFieldコントロールを使っています。