当我们使用搜索引擎时发现会有自动提示的功能,那么,它是怎么实现的呢?在jQuery中结合Ajax可以很容易实现自动完成的功能。
下面就在jQuery中使用Ajax提交post请求,让服务器端返回自动完成的数据显示在相应的div中。
编写html文件
主要是一个输入框,一个隐藏的div和提交按钮:
1 2 3 4 5 6 7 8
| <form id="register" method="post" action=""> <span class="tips">输入关键词:</span> <input type="text" name="keywords" class="keywords" /> <div class="list_box"> <div class="keywords_list"></div> </div> <input type="submit" id="submit" /> </form>
|
编写CSS样式
为了让显示效果更好看,编写如下CSS样式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <style type="text/css"> .tips { font-size:12px;} .list_box { position:relative; width:200px; margin-left:80px; background:#f3f3f3; border:1px solid #CCC; } .keywords_list { margin:0; padding:0; list-style:none; } .hover { background:#33CCFF; color:#333333; } </style>
|
jQuery代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <script type="text/javascript"> $(document).ready(function() { $('.list_box').hide(); $('.keywords').keyup(function(){ var keywords = $('keywords').val(); var data = 'keywords=' + keywords; $.ajax({ type:"POST", url:"autocomplete.php", data:data, success:function(html) { $('.list_box').show(); $('.keywords_list').html(html); $('li').hover(function(){ $(this).addClass('hover'); },function(){ $(this).removeClass('hover'); }); $('li').click(function(){ $('.keywords').val($(this).text()); $('.list_box').hide(); }); } }); return false; }); }); </script>
|
服务器端的响应程序
为了简单的验证可以编写以下php代码:
1 2 3 4
| echo '<li>arthinking</li>'; echo '<li>ajax</li>'; echo '<li>autoComplete</li>'; echo '<li>abc</li>';
|
也可以让服务器程序查询数据库,从相应的数据库中选择匹配的数据返回给客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13
| $keywords = $_POST['keywords']; $conn = mysql_connect("localhost", "root", "123") or die ("Please check your server connection."); mysql_select_db("autocomplete"); $query = "select keywords from index_list where keywords like '$keywords'"; $results = mysql_query($query) or die(mysql_error()); if($results) { while ($row = mysql_fetch_array($results)) { extract($row); echo '<li>' . $keywords. '</li>'; } }
|