到官方下载jquery-1.7.2.js和jquery-ui-1.8.22.costom.zip两个文件。(注意:不同版本写法不一样)
index.jsp页面代码如下:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page isELIgnored="false" %>
<fmt:requestEncoding value="UTF-8"/>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<c:set var="requestURI" value="${pageContext.request.servletPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>sou suo lecense</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery/ui/css/jquery.ui.all.css" />
<%--<link rel="stylesheet" type="text/css" href="${ctx}/css/demos.css" />--%>
<script type="text/javascript" src="${ctx}/js/jquery/jquery-1.7.2.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery/ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery/ui/jquery.ui.position.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery/ui/jquery.ui.autocomplete.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery/json2.js"></script>
<style type="text/css">
.ui-autocomplete {
max-width: 151px;
max-height: 200px;
overflow-y: auto;
overflow-x: hidden;
padding-right: 1px;
}
/* IE6 不支持下拉样式 */
* html .ui-autocomplete {
height: 100px;
}
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
#city { width: 25em; }
</style>
<script type="text/javascript">
jQuery(document).ready(function(){
//下面是简单的数组模式的数据格式
// var availableTags = ["ActionScript","AppleScript","Asp","BASIC","C","C++","Clojure","COBOL","ColdFusion","Erlang","Fortran","Groovy","Haskell","Java","JavaScript","Lisp","Perl","PHP","Python","Ruby","Scala","Scheme","我们","我爱我家","我是优派","shihuan","anjie","唯我独尊"];
// $("#mylike").autocomplete({
// source: availableTags
// });
//下面是带有分类的数组模式的数据格式
// $.widget( "custom.catcomplete", $.ui.autocomplete, {
// _renderMenu: function( ul, items ) {
// var self = this,
// currentCategory = "";
// $.each( items, function( index, item ) {
// if ( item.category != currentCategory ) {
// ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
// currentCategory = item.category;
// }
// self._renderItem( ul, item );
// });
// }
// });
//
// var data = [
// { label: "anders", category: "" },
// { label: "andreas", category: "" },
// { label: "antal", category: "" },
// { label: "annhhx10", category: "Products" },
// { label: "annk K12", category: "Products" },
// { label: "annttop C13", category: "Products" },
// { label: "anders andersson", category: "People" },
// { label: "andreas andersson", category: "People" },
// { label: "andreas johnson", category: "People" }
// ];
//
// var data1 = [
// { label: "anders", category: "" },
// { label: "andreas", category: "" },
// { label: "antal", category: "" },
// { label: "annhhx10", category: "" },
// { label: "annk K12", category: "" },
// { label: "annttop C13", category: "" },
// { label: "anders andersson", category: "" },
// { label: "andreas andersson", category: "" },
// { label: "andreas johnson", category: "" }
// ];
//
// $("#search").catcomplete({
// delay: 0,
// source: data1
// });
//下面是JSON数据类型的数据格式
function log(message) {
$("<div/>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#city").autocomplete({
source: function(request, response) {
$.ajax({
url: "user/manage/queryjsondata.do",
dataType: "json",
data: {myparam: "myp", mynum: 12, name_startsWith: request.term}, //传递给后台请求的参数
success: function(data) {
response( $.map(data, function(item) {
return {
//label: item.uid + (item.displayname ? ", " + item.displayname : "") + ", " + item.mail,
label: item.uid, //显示在匹配下拉框的内容
mytext: item.mail, //可以自定义,用来赋值给其他input框或div域
value: item.displayname //是返回值属性
}
}));
}
});
},
minLength: 2, //至少输入几个字符的时候开始匹配
select: function(event, ui) { //选中失去焦点后触发的事件
//log(ui.item ? "Selected: " + ui.item.label : "Nothing selected, input was " + this.value);
log(ui.item ? "Selected: " + ui.item.mytext : "Nothing selected, input was " + this.value);
$("#citycode").val(ui.item.value);
//$("#log").html(this.value);
},
open: function() { //在下拉框被显示的时候触发
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() { //在下拉框被隐藏的时候触发
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
/* 获取选中后input框中的value值 */
function getSearchVal(){
alert($("#search").val());
}
</script>
</head>
<body>
<%--
This is my JSP page. <br>
<form action="user/manage/queryuser.do" method="get">
<input type="submit" name="ok" value="ok" />
</form>
--%>
<div class="ui-widget">
<form action="" method="post">
<label for="mylike">模糊匹配: </label>
<input id="mylike" style="width:150px;" />
<label for="search">分类模糊匹配: </label>
<input id="search" style="width:150px;" />
<input type="button" name="btn" value="获取选中值" οnclick="getSearchVal();" />
<label for="city">Json数据匹配:</label>
<input id="city" style="width:300px;" />
<input type="text" id="citycode" />
</form>
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</body>
</html>
后台请求的Java代码如下:
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.shihuan.core.framework.control.BaseControl;
import com.shihuan.core.framework.query.PageUtil;
import com.shihuan.core.framework.query.ReportPage;
import com.shihuan.core.framework.utils.DecodeUtil;
import com.shihuan.core.framework.utils.OpMessage;
import com.shihuan.service.UserService;
@Controller
@RequestMapping(value = "user/manage")
public class UserCtrl extends BaseControl {
protected org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(getClass().getName());
@Autowired
private UserService userService;
@RequestMapping(value = "queryjsondata.do")
@ResponseBody
public void queryjsondata(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println(request.getParameter("myparam") + " -- " + request.getParameter("mynum") + " -- " + request.getParameter("name_startsWith"));
String jsondata = "[{\"uid\":\"123\", \"displayname\":\"my123\", \"mail\":\"mail123\"}, {\"uid\":\"456\", \"displayname\":\"my456\", \"mail\":\"mail456\"}, {\"uid\":\"789\", \"displayname\":\"my789\", \"mail\":\"mail789\"}]";
response.setContentType("text/plain; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().println(jsondata);
}
}
运行截图如下:
示例代码在笔者abcdef的163邮箱里。