web.xml:
<!-- DWR Servlet配置 -->
<servlet>
<servlet-name>dd</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dd</servlet-name>
<url-pattern>/xxx/*</url-pattern>
</servlet-mapping>
dwr.xml配置
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
"http://getahead.org/dwr/dwr20.dtd">
<dwr>
<allow>
<!-- CityService cityBiz = new com.service.CityService() -->
<create creator="new" javascript="cityBiz">
<param name="class" value="com.service.CityService" />
<include method="findNameByKey"/>
</create>
<convert converter="bean" match="com.entity.City" />
</allow>
</dwr>
后端Java 方法:
/**
* 根据关键字 搜索
*
*/
private String keys = "AAAaaa,zhang,zhangsan,zhaoyun,wanwu,wang,wangliu,zhafei";
public List<String> findNameByKey(String key){
System.out.println(">>>==="+key);
List<String> find = new ArrayList<String>();//保存符合条件的
String[] cs = keys.split(",");
for (String string : cs) {
if(string.startsWith(key)){
find.add(string);
}
}
return find;
}
auto.jps如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>百度-内容自动补全</title>
<script type="text/javascript" src="req.js"></script>
<script type='text/javascript' src='/ajax/xxx/interface/cityBiz.js'></script>
<script type='text/javascript' src='/ajax/xxx/engine.js'></script>
<script type="text/javascript">
var index = -1;
var oldValue;
function findKey(obj){
var v = obj.value;
//上下键时
if(event.keyCode==38 || event.keyCode==40){
var show = document.getElementById("show");
//获取显示列表的div元素对象
var div = show.getElementsByTagName("div");
if(event.keyCode==38){
index--;
if(index==-1){//为了和百度效果相同 添加的功能
obj.value = oldValue;
}else
if(index<0){
index=div.length-1;
}
}else{
index++;
if(index==div.length){//为了和百度效果相同 添加的功能
obj.value = oldValue;
}else
if(index>div.length){
index = 0;
}
}
//index=index%div.length;
//遍历div下所有的子div
for(var i=0;i<div.length;i++){
if(i==index){//如果等于当前选中的子div 则变背景色
div[i].style.background="gray";
obj.value=div[i].innerHTML;
}else{
div[i].style.background="white";
}
}
return;//上下键时,不在请求后台数据
}
//保存原有的key
oldValue = obj.value;
cityBiz.findNameByKey(v,function(data){
//获取事件源元素的位置
var left = obj.offsetLeft;
var top = obj.offsetTop;
var show = document.getElementById("show");
var height = obj.offsetHeight;
//初始化index
index = -1;
show.style.left = left;
show.style.top = top+height;
var str = "";
for(var i=0;i<data.length;i++){
str += "<div>"+data[i]+"</div>";
}
show.innerHTML = str;
});
}
</script>
</head>
<body>
<center>
<br>
<input name="key" οnkeyup="findKey(this)">
</center>
<div id="show" style="position: absolute "></div>
</body>
</html>