JSP + ajax实现输入框自动补全功能 实例代码
下面是我用ajax实现的输入框自动补全功能,数据库数据很少,大体模仿出了百度首页的提示功能,当然,人家百度的东西不只是这么简单的!先看运行效果:
index.jsp(包含主要的js代码)
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%
string path = request.getcontextpath();
string basepath = request.getscheme() + "://"
+ request.getservername() + ":" + request.getserverport()
+ path + "/";
%>
<!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>查找</title>
<script type="text/javascript">
function msift_seektp(oobj, ndire) {
var nposition = null;
if (oobj.getboundingclientrect && !document.all) {
var odc = document.documentelement;
switch (ndire) {
case 0:
return oobj.getboundingclientrect().top + odc.scrolltop;
case 1:
return oobj.getboundingclientrect().right + odc.scrollleft;
case 2:
return oobj.getboundingclientrect().bottom + odc.scrolltop;
case 3:
return oobj.getboundingclientrect().left + odc.scrollleft;
}
} else {
if (ndire == 1 || ndire == 3) {
nposition = oobj.offsetleft;
} else {
nposition = oobj.offsettop;
}
if (arguments[arguments.length - 1] != 0) {
if (ndire == 1) {
nposition += oobj.offsetwidth;
} else if (ndire == 2) {
nposition += oobj.offsetheight;
}
}
if (oobj.offsetparent != null) {
nposition += msift_seektp(oobj.offsetparent, ndire, 0);
}
return nposition;
}
}
function msift(cvarname, nmax) {
this.oo = cvarname;
this.max = nmax;
}
msift.prototype = {
varsion : 'v2010.10.29 by angusyoung | mrxcool.com',
target : object,
tglist : object,
listeners : null,
selindex : 0,
data : [],
redata : [],
create : function(oobj) {
var _this = this;
var oul = document.createelement('ul');
oul.style.display = 'none';
oobj.parentnode.insertbefore(oul, oobj);
_this.tglist = oul;
oobj.onkeydown = oobj.onclick = function(e) {
_this.listen(this, e);
};
oobj.onblur = function() {
settimeout(function() {
_this.clear();
}, 100);
};
},
complete : function() {
},
select : function() {
var _this = this;
if (_this.redata.length > 0) {
_this.target.value = _this.redata[_this.selindex].replace(
/\*/g, '*').replace(/\|/g, '|');
_this.clear();
}
settimeout(function() {
_this.target.focus();
}, 10);
_this.complete();
},
listen : function(oobj) {
var _this = this;
_this.target = oobj;
var e = arguments[arguments.length - 1];
var ev = window.event || e;
switch (ev.keycode) {
case 9://tab
return;
case 13://enter
_this.target.blur();
_this.select();
return;
case 38://up
_this.selindex = _this.selindex > 0 ? _this.selindex - 1
: _this.redata.length - 1;
break;
case 40://down
_this.selindex = _this.selindex < _this.redata.length - 1 ? _this.selindex + 1
: 0;
break;
default:
_this.selindex = 0;
}
if (_this.listeners) {
clearinterval(_this.listeners);
}
_this.listeners = setinterval(function() {
_this.get();
}, 10);
},
get : function() {
var _this = this;
if (_this.target.value == '') {
_this.clear();
return;
}
if (_this.listeners) {
clearinterval(_this.listeners);
}
;
_this.redata = [];
var cresult = '';
for ( var i = 0; i < _this.data.length; i++) {
if (_this.data[i].tolowercase().indexof(
_this.target.value.tolowercase()) >= 0) {
_this.redata.push(_this.data[i]);
if (_this.redata.length == _this.max) {
break;
}
}
}
var cregpattern = _this.target.value.replace(/\*/g, '*');
cregpattern = cregpattern.replace(/\|/g, '|');
cregpattern = cregpattern.replace(/\+/g, '\\+');
cregpattern = cregpattern.replace(/\./g, '\\.');
cregpattern = cregpattern.replace(/\?/g, '\\?');
cregpattern = cregpattern.replace(/\^/g, '\\^');
cregpattern = cregpattern.replace(/\$/g, '\\$');
cregpattern = cregpattern.replace(/\(/g, '\\(');
cregpattern = cregpattern.replace(/\)/g, '\\)');
cregpattern = cregpattern.replace(/\[/g, '\\[');
cregpattern = cregpattern.replace(/\]/g, '\\]');
cregpattern = cregpattern.replace(/\\/g, '\\\\');
var cregex = new regexp(cregpattern, 'i');
for ( var i = 0; i < _this.redata.length; i++) {
if (_this.target.value.indexof('*') >= 0) {
_this.redata[i] = _this.redata[i].replace(/\*/g, '*');
}
if (_this.target.value.indexof('|') >= 0) {
_this.redata[i] = _this.redata[i].replace(/\|/g, '|');
}
cresult += '<li style="padding:0 5px;line-height:20px;cursor:default;" onmouseover="'
+ _this.oo
+ '.changeon(this);'
+ _this.oo
+ '.selindex='
+ i
+ ';" onmousedown="'
+ _this.oo
+ '.select();">'
+ _this.redata[i]
.replace(
cregex,
function(s) {
return '<span style="background:#ff9;font-weight:bold;font-style:normal;color:#e60;">'
+ s + '</span>';
});
+'</li>';
}
if (cresult == '') {
_this.clear();
} else {
_this.tglist.innerhtml = cresult;
_this.tglist.style.csstext = 'display:block;position:absolute;background:#fff;border:#090 solid 1px;margin:-1px 0 0;padding: 5px;list-style:none;font-size:12px;';
_this.tglist.style.top = msift_seektp(_this.target, 2) + 'px';
_this.tglist.style.left = msift_seektp(_this.target, 3) + 'px';
_this.tglist.style.width = _this.target.offsetwidth - 12 + 'px';
}
var oli = _this.tglist.getelementsbytagname('li');
if (oli.length > 0) {
oli[_this.selindex].style.csstext = 'background:#36c;padding:0 5px;line-height:20px;cursor:default;color:#fff;';
}
},
changeon : function(oobj) {
var oli = this.tglist.getelementsbytagname('li');
for ( var i = 0; i < oli.length; i++) {
oli[i].style.csstext = 'padding:0 5px;line-height:20px;cursor:default;';
}
oobj.style.csstext = 'background:#36c;padding:0 5px;line-height:20px;cursor:default;color:#fff;';
},
clear : function() {
var _this = this;
if (_this.tglist) {
_this.tglist.style.display = 'none';
_this.redata = [];
_this.selindex = 0;
}
}
}
</script>
</head>
<body>
<form name="salefrm" method="post" action="result.jsp">
<input type="text" onfocus="loadxmldoc(this.value)" name="name" id="abc" size="40" />
<input type="submit" value="搜索" />
</form>
<script type="text/javascript">
//建立实例,第一个参数是实例对象的名称,第二个是最多显示的数量
var oo = new msift('oo', 20);
//获取数据
function loadxmldoc(str) {
var xmlhttp;
if (window.xmlhttprequest) {// code for ie7+, firefox, chrome, opera, safari
xmlhttp = new xmlhttprequest();
} else {// code for ie6, ie5
xmlhttp = new activexobject("microsoft.xmlhttp");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
oo.data = xmlhttp.responsetext.split("|");
}
};
xmlhttp.open("get", "ajaxservlet?name="+str, true);
xmlhttp.send();
}
//指定文本框对象建立特效
oo.create(document.getelementbyid('abc'));
</script>
</body>
</html>
ajaxservlet.java
public void doget(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
response.setcontenttype("text/xml; charset=utf-8");
printwriter out = response.getwriter();
string str = newsdao.findallnewstype();
out.println(str);
}
以上就是主要代码,数据库查询后返回的是以"|"分割连接的字符串组合(ps:图省劲嘛)。