AJAX 搜索自动显示练习
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script src="jquery-1.11.2.min.js"></script> <style type="text/css"> *{ margin:0px auto; padding:0px} #xianshi{ width:300px; margin-top:20px} #txt{ width:300px} #name{ width:296px} #list{ width:300x; position:absolute; z-index:3;} .sj{ width:298px; height:19px; border:1px solid #0FF; border-top:0px; background-color:#FFF;} .sj:hover{ cursor:pointer} #fg{ margin:30px 0px 20px 0px;} </style> </head> <body> <div id="xianshi"> <div id="txt"> <input type="text" id="name" /> </div> <div id="list"> </div> </div> <hr id="fg" /> <table id="tb" width="100%" border="1" cellpadding="0" cellspacing="0"> </table> </body> <script type="text/javascript"> $(document).ready(function(e) { xianshi(); //输入内容显示下拉 $("#name").keyup(function(){ var key=$(this).val(); $.ajax({ async:false, url:"AJAX5chuli.php", data:{key:key,bs:0}, type:"POST", dataType:"TEXT", success: function(data){ if(data.trim()=="") { $("#list").html(""); } else { var shuju=data.trim().split("|"); var str=""; for(var i=0;i<shuju.length;i++) { shuju[i]; str=str+"<div class='sj'>"+shuju[i]+"</div>" } $("#list").html(str); $(".sj").css("display","block"); } } }) //鼠标放上显示背景色 $(".sj").mouseover(function(){ $(".sj").css("background-color","#FFF"); $(this).css("background-color","#0F0"); }); //鼠标离开去掉背景色 $(".sj").mouseout(function(){ $(this).css("background-color","#FFF"); }); //点击将选中项的值放到文本框 $(".sj").click(function(){ var txt=$(this).text(); $("#name").val(txt); $(".sj").css("display","none"); xianshi(); }) xianshi(); }) }); //查询所有数据显示表格 function xianshi() { var key=$("#name").val(); $.ajax({ url:"AJAX5chuli.php", data:{key:key,bs:1}, type:"POST", dataType:"TEXT", success: function(data){ var hang=data.trim().split("|"); var str="<tr><td>汽车名称</td><td>系列</td><td>上市时间</td><td>油耗</td><td>价格</td></tr>"; for(var i=0;i<hang.length;i++) { var lie=hang[i].split("^"); str=str+"<tr><td>"+lie[1]+"</td><td>"+lie[2]+"</td><td>"+lie[3]+"</td><td>"+lie[4]+"</td><td>"+lie[7]+"</td></tr>"; } $("#tb").html(str); } }) } </script> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php include("DBDA.php"); $db=new DBDA(); $bs=$_POST["bs"]; $key=$_POST["key"]; if($bs==1) { $sql="select * from car where name like '%{$key}%'"; echo $db->StrQuery($sql); } else { if($key=="") { echo ""; } else { $sql="select name from car where name like '%{$key}%'"; echo $db->StrQuery($sql); }; };