Ajax实现搜索功能

前端之家收集整理的这篇文章主要介绍了Ajax实现搜索功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

显示效果如下:

原文链接:https://www.f2er.com/ajax/164514.html

猜你在找的Ajax相关文章