Ajax在搜索功能应用还是比较广泛的,例如百度搜索输入框,输入一个字会跟着显示很多相似的文字。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax实现搜索功能</title> <style> #content{ width:400px; height:400px; border:2px outset #eeeeee; display:none; } </style> <script type="text/javascript" src="public.js"></script> <script> window.onload=function(){ $('word').onkeyup=function(){ var word=this.value; //用户输入的内容 $('content').innerHTML=''; if(word.length==0){ $('content').style.display='none'; return; } $.get('search.PHP','word='+word,function(msg){ var length=msg.length; if(length>0) $('content').style.display='block'; else $('content').style.display='none'; for(var i=0;i<length;i++){ var name=msg[i].name; //第i个分类名称 var div=document.createElement('div'); div.onmouSEOver=function(){ this.style.backgroundColor='#cc6699'; } div.onmouSEOut=function(){ this.style.backgroundColor='#ffffff'; } div.onclick=function(){ $('word').value=this.innerHTML; $('content').style.display='none'; }; div.innerHTML=name; $('content').appendChild(div); } },'json'); }; }; </script> </head> <body> <input type="text" id="word" size="50"/><input type="submit" value="搜索"/> <div id="content"> </div> </body> </html>
<?PHP $word=$_GET['word']; $sql="select name from category where name like '$word%' order by id desc"; MysqL_connect('localhost','root','root'); MysqL_select_db('test'); MysqL_query('set names utf8'); $result=MysqL_query($sql); $num=MysqL_num_rows($result); $data=array(); for($i=0;$i<$num;$i++){ $row=MysqL_fetch_assoc($result); $row['name']=iconv('utf-8','utf-8',$row['name']); $data[]=$row; } MysqL_close(); echo json_encode($data);
显示效果如下: