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: 150,//提示框的宽度
delimiter: /(,|;)\s*/,//分隔符
deferRequestBy: 0, //单位微秒
zIndex: 9999,
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: 1px solid #999; background: #FFF; cursor: default; overflow: auto; -webkit-box-shadow: 1px 4px 3px rgba(50, 50, 50, 0.64); -moz-box-shadow: 1px 4px 3px rgba(50, 50, 50, 0.64); box-shadow: 1px 4px 3px rgba(50, 50, 50, 0.64); }
.autocomplete-suggestion { padding: 2px 5px; white-space: nowrap; overflow: hidden; }
.autocomplete-no-suggestion { padding: 2px 5px;}
.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。