jQuery有很多很多的已经实现,很漂亮的插件,autocomplete就是其中之一。jQuery ui autocomplete主要支持字符串Array、JSON两种数据格式。
主要参数:
Source:数据源,类型为String、Array、Function,其中String为ajax请求的服务器端地址,返回Array/JSON格式,Array即为数组,静态定义到页面中的数据,下面会有具体的
demo,Function(request,response):通过request.term获得输入的值,response(Array)来呈现数据(JSONP是这种方式);
minLength:当输入框内字符串长度达到minLength时,激活Autocomplete
autoFocus:当autocomplete选择菜单弹出时,自动选中第一个。
delay:即延迟多少毫秒autocomplete
disabled:是否禁用自动完成功能,默认false
jQuery ui提供的常用方法:
close():关闭智能提示框
destory():销毁智能提示框,将其所产生的元素完全删除,使其恢复至初始状态
disable():禁用自动完成功能
enable():开启自动完成功能
主要事件:
change(event,ul):当值改变时发生,ui.item为选中项
close(event,ui):当智能提示框关闭时发生
create(event,ui):当智能提示框创建时发生,可以在此事件中,对外观进行控制
focus(event,ui):当智能提示列表任意一项获得焦点时发生,ui.item为获得焦点的项
open(event,ui):当智能提示框打开或更新时发生
response(event,ui):在搜索完成之后智能提示框显示前发生,可以在此时间中对显示项进行处理
search(event,ui):在开始请求之前发生,可以在此事件中返回false来取消请求
select(event,ui):当智能提示框中任意一项被选中时发生,ui.item为选中项
使用时应首先需要导入相关的js文件
下载:http://jqueryui.com/autocomplete/ jquery ui相关js ,下载后的文件external文件夹下有jquery的核心js
第一种获取数据源方式:String,即通过字符串发送ajax,本例为了省事,直接就使用了原始的servlet,没有用到框架,只是演示效果
数据库(略)
dao
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class Dao {
private static Connection getConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/itac", "root", "root");
}
public static List<String> getNames(String username) throws Exception{
Connection c = getConnection();
Statement stat = c.createStatement();
ResultSet rs = stat.executeQuery("select user_name from t_user where user_name like '%"+username+"%'");
List<String> strs = new ArrayList<String>();
while(rs.next()){
strs.add(rs.getString("user_name"));
}
return strs;
}
}
package com.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.Dao;
@WebServlet(name="autoServlet",value="/auto")
public class AutoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");//解决乱码
String username = request.getParameter("term");//默认传过来的参数名成为term,封装了文本框中输入的值
StringBuffer sb = new StringBuffer("[");
try {
List<String> names = Dao.getNames(username);
for(int i=0;i<names.size();i++){
if(i==names.size()-1){
//注意在拼接的时候,要用双引号,单引号我试过,不起作用好像是,至少key必须是双引号,最好都写成双引号
/*
* 其中label属性用于显示在autocomplete弹出菜单,而value属性则是选中后给文本框赋的值。如果没有指定其中一个属性
* 则用另一个属性替代(即value和label值一样),如果label和value都没有指定,则无法用于autocomplete的提示。
*/
sb.append("{\"lable\":\""+names.get(i)+"\",\"value\":\""+names.get(i)+"\"}]");
}else{
sb.append("{\"lable\":\""+names.get(i)+"\",\"value\":\""+names.get(i)+"\"},");
}
}
System.out.println(sb.toString());
response.getWriter().write(sb.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link href="${pageContext.request.contextPath }/resources/css/jquery-ui.css" rel="stylesheet">
<style>
body{
font: 62.5% "Trebuchet MS", sans-serif;
margin: 50px;
}
</style>
<script src="${pageContext.request.contextPath }/resources/js/jquery.js"></script>
<script src="${pageContext.request.contextPath }/resources/js/jquery-ui.js"></script>
<%-- <script src="${pageContext.request.contextPath }/resources/js/jquery.ui.core.js"></script>
<script src="${pageContext.request.contextPath }/resources/js/jquery.ui.autocomplete.js"></script>
<script src="${pageContext.request.contextPath }/resources/js/jquery.ui.position.js"></script>
<script src="${pageContext.request.contextPath }/resources/js/jquery.ui.widget.js"></script> --%>
</head>
<body>
<input id="username" type="text" value="" name="username"/>
</body>
<script type="text/javascript">
//String方式
$(function(){
$("#username").autocomplete({
source:"<c:url value="/auto"/>",
minLength:1
});
});
</script>
</html>
第二种获取数据源方式:回调函数
dao
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import domain.User;
public class Dao2 {
private static Connection getConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/itac", "root", "root");
}
public static List<User> getNames(String username) throws Exception{
Connection c = getConnection();
Statement stat = c.createStatement();
ResultSet rs = stat.executeQuery("select * from t_user where user_name like '%"+username+"%'");
List<User> users = new ArrayList<User>();
while(rs.next()){
User u = new User();
u.setUserId(Integer.parseInt(rs.getString("user_id")));
u.setUserName(rs.getString("user_name"));
u.setBirth(rs.getString("user_date"));
users.add(u);
}
return users;
}
}
User.java
package domain;
public class User {
private Integer userId;
private String userName;
private String birth;
//getter setter tostring
}
package com.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.Dao2;
import com.google.gson.Gson;
import domain.User;
/**
* Servlet implementation class AutoServlet2
*/
@WebServlet("/auto2")
public class AutoServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
System.out.println(request.getParameter("userName"));
try {
List<User> users = Dao2.getNames(request.getParameter("userName"));
Gson gson = new Gson();
String str = gson.toJson(users);
response.getWriter().write(str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link href="${pageContext.request.contextPath }/resources/css/jquery-ui.css" rel="stylesheet">
<style>
body{
font: 62.5% "Trebuchet MS", sans-serif;
margin: 50px;
}
</style>
<script src="${pageContext.request.contextPath }/resources/js/jquery.js"></script>
<script src="${pageContext.request.contextPath }/resources/js/jquery-ui.js"></script>
</head>
<body>
<input type="text" name="userName" id="userName"/>
</body>
<script type="text/javascript">
$("#userName").autocomplete({
source: function( request, response ) {
$.ajax({
type:"post",
url: "<c:url value="/auto2"/>",
dataType: "json",
data:{
userName: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return { //lable为下拉列表显示数据源。value为选中放入到文本框的值,这种方式可以自定义显示
lable:item.userName,
value: item.userName
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) { //移动键盘上下键,自动将下拉列表的数据放入到文本框,不过不写这个配置也是可以的,默认就行,具体这个还不知道是做什么
$("#userName").val(ui.item.userName);
}
});
</script>
</html>
第三种方式较简单,直接在页面上放入,比如:
// 本地json数组
var availableTagsJSON = [
{ label: "C# Language", value: "C#" },
{ label: "C++ Language", value: "C++" },
{ label: "Java Language", value: "Java" },
{ label: "JavaScript Language", value: "JavaScript" },
{ label: "ASP.NET", value: "ASP.NET" },
{ label: "JSP", value: "JSP" },
{ label: "PHP", value: "PHP" },
{ label: "Python", value: "Python" },
{ label: "Ruby", value: "Ruby" }
];
$("#local").autocomplete({
source: availableTagsJSON
});