加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax实现搜索功能

发布时间:2020-12-16 00:25:01 所属栏目:百科 来源:网络整理
导读:Ajax在搜索功能应用还是比较广泛的,例如百度搜索输入框,输入一个字会跟着显示很多相似的文字。 接下来是用PHP+MySQL+Ajax实现功能 !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"htmlheadmeta ht

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);

显示效果如下:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读