输入某一个字,自动提示,具体步骤如下:
1.导入jquery插件及样式:
<link rel="stylesheet" href="${basepath}plugins/jquery-ui-1.9.2/css/jquery.ui.all.css">
<script src="${basepath}plugins/jquery-ui-1.9.2/js/jquery-1.8.3.js"></script>
<script src="${basepath}plugins/jquery-ui-1.9.2/js/jquery.ui.core.js"></script>
<script src="${basepath}plugins/jquery-ui-1.9.2/js/jquery.ui.widget.js"></script>
<script src="${basepath}plugins/jquery-ui-1.9.2/js/jquery.ui.position.js"></script>
<script src="${basepath}plugins/jquery-ui-1.9.2/js/jquery.ui.menu.js"></script>
<script src="${basepath}plugins/jquery-ui-1.9.2/js/jquery.ui.autocomplete.js"></script>
<link rel="stylesheet" href="${basepath}plugins/jquery-ui-1.9.2/css/demos.css">
2.在页面中增加如下元素:
<input type="text" name="author" id="author">
<input type="hidden" name="author" id="authorId" >
3.在页面中增加如下脚本:
<script>
$(function() {
$( "#author" ).autocomplete({
minLength: 0,
source: function( request, response ) {
$.ajax({
url: "${BasePath}/exercise/exercise!getTeacherAjax.action",
dataType: "json",
data: {
maxRows: 10,
queryName: $("#author").val()
},
success: function(data) {
if(data != null){
response( $.map(data, function( item ) {
return {
label: item.realName + "【用户名:"+ (item.userName==''?' ': item.userName)+ ",学段:"+ (item.periodName==''?' ':item.periodName) + ",学科:" + (item.subjectName==''?' ':item.subjectName) +"】",
desc: item.realName,
value: item.id
}
}));
}
}
});
},
focus: function( event, ui ) {
$( "#author" ).val( ui.item.desc );
return false;
},
select: function( event, ui ) {
$( "#author" ).val( ui.item.desc );
$( "#authorId" ).val( ui.item.value );
return false;
}
});
});
</script>
4.调用的action方法如下:
public String getTeacherAjax(){
System.out.println("queryName:" + queryName);
String teacherJson ="";
try {
teacherJson = teacherService.getTeacherJson(queryName);
} catch (Exception e) {
e.printStackTrace();
}
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType(type + ";charset=UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().write(content);
response.getWriter().flush();
return null;
}
注意: teacherJson 为json格式
此方法是根据:custom data and display改写而成。