Ajax在搜索功能应用还是比较广泛的,例如百度搜索输入框,输入一个字会跟着显示很多相似的文字。
接下来是用PHP+MySQL+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获取数据库中的数据
- <?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);
显示效果如下:
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。