本文要介绍的jquery autocomplete是jquery ui的。需要的库从jquery ui官网下载
后台只要返回一个json格式的字符串数组
注:采用spring mvc
@ResponseBody
@RequestMapping(value=”/autoComplete”,method = RequestMethod.POST)
public List<String> autoComplete(HttpServletRequest request){
String keyword = request.getParameter(“keyword”);
List<String> list = this.studentService.getNameByName(keyword);//从数据库查询出姓名
return list;
}
页面关键代码
<!–引入jquery ui的样式–>
<link rel=”stylesheet” href=”../css/jquery-ui.css” />
<!–引入jquery ui库–>
<script type=”text/javascript” src=”../js/jquery-ui.js”></script>
<input type=”text” name=”keyword” id=”keyword” value=””
class=”inp_srh” placeholder=”搜索姓名”/>
插件调用
$(“#keyword”).autocomplete({
minLength : 1,
autoFocus : true,
source : function(request, response) {
$.ajax({
type : “POST”,
url : “autoComplete”,//从后台获取数据
dataType : “json”,
data : {
keyword : $(“#keyword”).val()
},
success : function(json) {
response($.map(json, function(item) {
return {
label : item,
value : item
};
}));
}
});
}
}); //
通过上面几个片段代码,实际基本完成了自动提示
它有很多的配置,了解更多配置看官方文档