ajax之搜索提示

来源:岁月联盟 编辑:exp 时间:2009-01-09
数据库表: 复制内容到剪贴板
代码:

CREATE TABLE `xqbar`.`suggest` (
`id` INT NOT NULL AUTO_INCREMENT ,
`title` VARCHAR( 100 ) NOT NULL ,
`hits` INT NOT NULL DEFAULT '0',
PRIMARY KEY ( `id` )
) ENGINE = InnoDB

insert into suggest(title,hits)values('xqbar.com',100);
insert into suggest(title,hits)values('www.xqbar.com',410);
insert into suggest(title,hits)values('http://xqbar.com',700);
insert into suggest(title,hits)values('mail:xqbar.com',200);
insert into suggest(title,hits)values('ftp:xqbar.com',100);
insert into suggest(title,hits)values('http://www.xqbar.com',70)search.php
(关于php我也是接触不久,下面的php如果罗嗦还望高手指点)
返回的信息字符串要为 xxx1|xxx2$200|100 前后对应 复制内容到剪贴板
代码:

<?php
if($_GET["action"]!=''){
#获取用户输入的关键字
$keyword=$_GET["keyword"];
#过滤关键字
$keyword=str_replace("[","[[]",$keyword);
$keyword=str_replace("&","[&]",$keyword);
$keyword=str_replace("%","[%]",$keyword);
$keyword=str_replace("^","[^]",$keyword);
#链接数据库
$conn=mysql_connect("localhost","xqbar","xqbaradmin");
#选择数据库
@mysql_select_db("xqbar") or die('sorry');
mysql_query('set names utf-8');
#查询语句
$sql="select title,hits from suggest where title like '%".$keyword."%' order by hits desc limit 10";
$result=mysql_query($sql);
#循环得到查询结果,返回字符串
#格式为 结果1|结果2$结果1点击次数|结果2点击次数
if($result){
$i=1;$title='';$hits='';
while($row=mysql_fetch_array($result,MYSQL_BOTH))
{
$title=$title.$row['title'];
$hits=$hits.$row['hits'];
if($i<mysql_num_rows($result))
{
$title=$title."|";
$hits=$hits."|";
}
$i++;
}
}
mysql_close();
}
?>
<?php echo $title.'$'.$hits;?>js代码 复制内容到剪贴板
代码:


引入prototye.js有朋友说这个库太大,或者把,不习惯的朋友可以使用jquery.js框架或者直接创建ajax对象,这个我就不想说了,这里直接引用prototye.js框架
<script type="text/javascript" src="prototype.js"></script>
创建层和显示查询结果的js代码
<script type="text/javascript">
//定义变量lastindex 表示为鼠标在查询结果上滑动所在位置,初始为-1
var lastindex=-1;
//定义变量flag 表示是否根据用户输入的关键字进行ajax查询,flase为允许查询 true为禁止查询
var flag=false;
//返回的查询结果生成的数组长度
var listlength=0;
//创建自定字符串,优化效率
function StringBuffer(){this.data=[];}
//赋值
StringBuffer.prototype.append=function(){this.data.push(arguments[0]);return this;}
//输出
StringBuffer.prototype.tostring=function(){return this.data.join("");}
//去掉字符串两边空格
String.prototype.Trim = function(){return this.replace(/(^/s*)|(/s*$)/g, "");}
//隐藏函数 主要是隐藏显示的提示下拉层和iframe,关于iframe下面在说其作用
function hiddensearch()
{
$('rlist').style.display="none";
$('rFrame').style.display="none";
}
//显示函数 主要是显示的提示下拉层和iframe 参数num,根据该参数控制要显示提示层和iframe的高度
function showsearch(num)
{
$('rlist').style.display='';
$('rFrame').style.display='';
//这里我定义每个返回查询结果的提示高度为20px,其中提示层总高度又加了num,是因为我在定义样式时使用了padding一个像素
$('rlist').style.height=num*20+num+'px';
//同样定位iframe的高度
$('rFrame').style.height=num*20+num+'px';
}
//返回文本输入框的坐标函数,参数element为要返回的对象,参数offset可选为offsetLeft|offsetTop 分别表示为该对象距离左窗口上角的绝对位置
//www.xker.com 利用这个函数可以定位我们要显示的提示层位置,使提示层正确的显示在文本输入框下面
function getposition(element,offset)
{
var c=0;
while(element)
{
c+=element[offset];
element=element.offsetParent
}
return c;
}
//创建提示层函数 包括提示层和为了避免在文本输入框下面出现select下拉选框时我们的提示层不能再select之上的iframe
//可以理解为当文本输入框下有select下拉选框时从底向上依次为 select下拉选框-iframe-提示层
function createlist()
{
//创建提示层
var listDiv=document.createElement("div");
//提示层id
listDiv.id="rlist";
listDiv.style.zIndex="2";
listDiv.style.position="absolute";
listDiv.style.border="solid 1px #000000";
listDiv.style.backgroundColor="#FFFFFF";
listDiv.style.display="none";
listDiv.style.width=$('keyword').clientWidth+"px";
listDiv.style.left=getposition($('keyword'),'offsetLeft')+1.5+"px";
listDiv.style.top =(getposition($('keyword'),'offsetTop')+$('keyword').clientHeight +3)+"px";

var listFrame=document.createElement("iframe");
listFrame.id="rFrame";
listFrame.style.zIndex="1";
listFrame.style.position="absolute";
listFrame.style.border="0";
listFrame.style.display="none";
listFrame.style.width=$('keyword').clientWidth+"px";
listFrame.style.left=getposition($('keyword'),'offsetLeft')+1+"px";
listFrame.style.top =(getposition($('keyword'),'offsetTop')+$('keyword').clientHeight +3)+"px";
document.body.appendChild(listDiv);
document.body.appendChild(listFrame);
}
function setstyle(element,classname)
{
switch (classname)
{
case 'm':
element.style.fontSize="12px";
element.style.fontFamily="arial,sans-serif";
element.style.backgroundColor="#3366cc";
element.style.color="black";
element.style.width=$('keyword').clientWidth-2+"px";
element.style.height="20px";
element.style.padding="1px 0px 0px 2px";
if(element.displaySpan)element.displaySpan.style.color="white"
break;
case 'd':
element.style.fontSize="12px";
element.style.fontFamily="arial,sans-serif";
element.style.backgroundColor="white";
element.style.color="black";
element.style.width=$('keyword').clientWidth-2+"px";
element.style.height="20px";
element.style.padding="1px 0px 0px 2px";
if(element.displaySpan)element.displaySpan.style.color="green"
break;
case 't':
element.style.width="80%";
if(window.navigator.userAgent.toLowerCase().indexOf("firefox")!=-1)element.style.cssFloat="left";
else element.style.styleFloat="left";
element.style.whiteSpace="nowrap";
element.style.overflow="hidden";
element.style.textOverflow="ellipsis";
element.style.fontSize="12px";
element.style.textAlign="left";
break;
case 'h':
element.style.width="20%";
if(window.navigator.userAgent.toLowerCase().indexOf("firefox")!=-1)element.style.cssFloat="right";
else element.style.styleFloat="right";
element.style.textAlign="right";
element.style.color="green";
break;
}
}
function focusitem(index)
{
if($('item'+lastindex)!=null)setstyle($('item'+lastindex),'d');
if($('item'+index)!=null)
{
setstyle($('item'+index), 'm');
lastindex=index;
}
else $("keyword").focus();
}
function searchclick(index)
{
$("keyword").value=$('title'+index).innerHTML;
flag=true;
}
function searchkeydown(e)
{
if($('rlist').innerHTML=='')return;
var keycode=(window.navigator.appName=="Microsoft Internet Explorer")?event.keyCode:e.which;
//down
if(keycode==40)
{
if(lastindex==-1||lastindex==listlength-1)
{
focusitem(0);
searchclick(0);
}
else{
focusitem(lastindex+1);
searchclick(lastindex+1);
}
}
if(keycode==38)
{
if(lastindex==-1)
{
focusitem(0);
searchclick(0);
}
else{
focusitem(lastindex-1);
searchclick(lastindex-1);
}
}
if(keycode==13)
{
focusitem(lastindex);
$("keyword").value=$('title'+lastindex).innerText;
}
if(keycode==46||keycode==8){flag=false;ajaxsearch($F('keyword').substring(0,$F('keyword').length-1).Trim());}
}
function showresult(xmlhttp)
{
var result=unescape(xmlhttp.responseText);
if(result!=''){
var resultstring=new StringBuffer();
var title=result.split('$')[0];
var hits=result.split('$')[1];
for(var i=0;i<title.split('|').length;i++)
{
resultstring.append('<div id="item'+i+'" onmousemove="focusitem('+i+')" onmousedown="searchclick('+i+')">');
resultstring.append('<span id=title'+i+'>');
resultstring.append(title.split('|'));
resultstring.append('</span>');
resultstring.append('<span id=hits'+i+'>');
resultstring.append(hits.split('|'));
resultstring.append('</span>');
resultstring.append('</div>');
}
$('rlist').innerHTML=resultstring.tostring();
for(var j=0;j<title.split('|').length;j++)
{
setstyle($('item'+j),'d');
$('item'+j).displaySpan=$('hits'+j);
setstyle($('title'+j),'t');
setstyle($('hits'+j),'h');
}
showsearch(title.split('|').length);
listlength=title.split('|').length;
lastindex=-1;
}
else hiddensearch();
}
function ajaxsearch(value)
{
new Ajax.Request('search.php',{method:"get",parameters:"action=do&keyword="+escape(value),onComplete:showresult});
}
function main()
{
$('keyword').className=$('keyword').className=='inputblue'?'inputfocus':'inputblue';
if($F('keyword').Trim()=='')hiddensearch();
else
{
if($F('keyword')!=''&&flag==false)ajaxsearch($F('keyword').Trim());
if(listlength!=0)$('keyword').onkeydown=searchkeydown;
else hiddensearch();
}
}
function oninit()
{
$('keyword').autocomplete="off";
$('keyword').onfocus=main;
$('keyword').onkeyup=main;
$('keyword').onblur=hiddensearch;
createlist();
}
Event.observe(window,'load',oninit);
</script>搜索框 复制内容到剪贴板
代码:

<form id="form1" name="form1" method="post" action="">
 <b>输入搜索关键字</b>
<input name="keyword" type="text" class="inputblue" id="keyword" maxlength="20" style="width:300px;" />
</form>