LoginSignup
4
4

More than 5 years have passed since last update.

【jQuery】AutoComplete機能の実装手順【Java/Spring】

Last updated at Posted at 2017-09-04

まず以下を読み込む

<link type="text/css" rel="stylesheet"
  href="http://code.jquery.com/ui/1.10.3/themes/cupertino/jquery-ui.min.css" />
<script type="text/javascript"
  src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript"
  src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>

サンプルコード

autocomplete.js
$(function(){
    /** プロジェクト名が変更になっても修正が必要なくなるよう実装**/
    var pathname = location.pathname.split("/")[1];

    $.ajax({
        /** オートコンプリート用のリストを取得するURL*/
        url: "/" + pathname + "/getAutoComplete",
        dataType: "json",
        type: 'GET'
    }).then(function(searchResult){ /** 検索結果のリストは引数に自動で入る*/
        $('.txtKeywd').autocomplete({ /** 実装したい入力欄のid/classを指定*/
            source : searchResult, /** 候補リスト(必須)*/
            autoFocus: true, /**リスト表示に際してリスト先頭にフォーカスするか*/
            delay: 500, /**キー入力からリスト表示までの遅延時間(ミリ秒)*/
            minLength: 1 /**オートコンプリート機能が働く最小文字数*/
        });
        },function(){
    });
});
GetAutoCompleteController.java
import net.arnx.jsonic.JSON;

/** 商品検索フォームのオートコンプリート用コントローラ. */
@Controller
@RequestMapping("/getAutoComplete")
public class GetAutoCompleteController {

    /** 全商品名をオートコンプリートに渡す. */
    @ResponseBody
    @RequestMapping
    public String getAutoComplete(){
        List<String> nameList = getAutoCompleteService.getAllNameList();
        return JSON.encode(nameList);
    }
}

注意点

  • JSONのエンコーダはJSONICを使用していますので、dependencyタグはコチラから入手してpom.xmlに追加
    https://mvnrepository.com/artifact/net.arnx/jsonic

  • JSON.encode()に何を渡すか
    ドメイン:オブジェクトを渡すとフィールド名をキーとするマップ(連想配列)をjsのsarchResultに渡す)
    リストオブジェクト:リストをそのままjsのsarchResultに渡す)

参考

autoFocus: 候補メニューの最初の候補に自動フォーカス
delay: 入力されて検索実行までのディレイ時間
minLength: 候補表示するための最低の入力文字数

その他のオプションについては、以下を参考。
Autocomplete Widget | jQuery UI API Documentation

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4