數據庫建表:
- 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(返回的字符串需要為 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.devdao.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>