jquery.autocomplete.js這個插件使用起來還是比較友善的,這裡隻介紹一下最實用的。通過ajax讀取資料在頁面呈現。
jsp頁面主要代碼:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><Document></Document></title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/styles/jquery.autocomplete.css" type="text/css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery.autocomplete.js"></script>
<script>
$(function(){
$("#groupName").autocomplete({
serviceUrl: "${pageContext.request.contextPath}/numGroupInfo/getAllnumgroupInfoJson.do",
width: ,//提示框的寬度
delimiter: /(,|;)\s*/,//分隔符
deferRequestBy: , //機關微秒
zIndex: ,
noCache: false,//是否啟用緩存 預設是開啟緩存的
onSelect: function (suggestions) {
}
});
});
</script>
</head>
<body>
<div>
<input type="text" name="groupName" id="groupName" />
</div>
</body>
</html>
jquery.autocomplete.js可以到https://github.com/devbridge/jQuery-Autocomplete中下載下傳一下,這上面也有更加詳細的講解,我就是根據這上面的寫的。css裡面也有,我隻用了自帶的:
.autocomplete-suggestions { border: px solid #999; background: #FFF; cursor: default; overflow: auto; -webkit-box-shadow: px px px rgba(, , , ); -moz-box-shadow: px px px rgba(, , , ); box-shadow: px px px rgba(, , , ); }
.autocomplete-suggestion { padding: px px; white-space: nowrap; overflow: hidden; }
.autocomplete-no-suggestion { padding: px px;}
.autocomplete-selected { background: #F0F0F0; }
.autocomplete-suggestions strong { font-weight: normal; color: #3399FF; }
在背景中查詢:
private class Minuser{
private Integer date;
private String value;
@SuppressWarnings("unused")
public Integer getDate() {
return date;
}
public void setDate(Integer date) {
this.date = date;
}
@SuppressWarnings("unused")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@RequestMapping(value = "/getAllnumgroupInfoJson")
public @ResponseBody void getAllnumgroupInfoJson(HttpServletResponse res,String query) {
List<NumGroupInfoTable> numGroupInfos = numGroupInfoService.getAllnumgroupInfo(query);
List<Minuser> minList = new ArrayList<Minuser>();
for(NumGroupInfoTable numGroupInfo : numGroupInfos){
Minuser minuser = new Minuser();
minuser.setDate(numGroupInfo.getGroupId());
minuser.setValue(numGroupInfo.getGroupName());
minList.add(minuser);
}
try {
Map<String, Object> map = new HashMap<String, Object>();
map.put("query", query);
map.put("suggestions", minList);
renderJSON(map,res);
} catch (IOException e) {
e.printStackTrace();
}
}
/*json*/
public void renderJSON(Object obj,HttpServletResponse res) throws IOException {
String json = new Gson().toJson(obj);
res.setCharacterEncoding("UTF-8");
res.setContentType("application/json;charset=UTF-8");
PrintWriter out = res.getWriter();
out.print(json);
out.flush();
out.close();
}
- 這一段代碼中的query參數是前台直接傳過來的輸入的參數,根據這個參數進行模糊查詢
- 主要的思想就是根據query參數進行查詢,然後把結果集轉換為json。