Posted in Javascript onDecember 15, 2009
于工作中需要用到自动提示这个功能,呵呵,自己又是js小菜,于是百度了一下,找到一个用jquery与其插件autocomplete开发的.net版的自动完成功能,于是down下来了改成了php版的,并加了支持向上/向下选择文字等功能,放上来共享一下,纯体力活。。。 :)
1、下载jquery库,网址:http://jquery.com/ ;
2、下载jquery autocomplete插件或者直接使用我附件里提供的文件,自己下载下来的文件需要修改一些内容才能支持向上/向下选择文字、解决中文乱码,其中解决中文乱的问题网上有提到过,就是把文件中的encodeURI改成escape,还有把keydown修改成keyup即可,至于支持向上/向下选择文字请参看附件;
3、以下是调用代码:
auto.html内容:
<!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=gb2312" /> <script type="text/javascript" src="include/javascript/jquery.js"></script> <script type="text/javascript" src="include/javascript/jquery.autocomplete.js"></script> <link rel="stylesheet" type="text/css" href="include/javascript/jquery.autocomplete.css" /> <title>自动完成测试</title> </head> <body> <input type="text" name="keyword" id="search" size="30" /> <script language="javascript"> $(document).ready(function() { $("#search").autocomplete( "getindex.php", { delay:10, minChars:1, matchSubset:1, matchContains:1, cacheLength:10, onItemSelect:selectItem, onFindValue:findValue, formatItem:formatItem, autoFill:false } ); }); function findValue(li) { if( li == null ) return alert("No match!"); if( !!li.extra ) var sValue = li.extra[0]; else var sValue = li.selectValue; } function selectItem(li) { findValue(li);} function formatItem(row) { return row[0];//return row[0] + " (id: " + row[1] + ")"//如果有其他参数调用row[1],对应输出格式Sparta|896 } function lookupAjax(){ var oSuggest = $("#search")[0].autocompleter; oSuggest.findValue(); return false; } </script> </body> </html>
getindex.php
<?php header("ContentType:text/plain;charset:gb2312"); define('SCRIPTNAV', 'getindex'); require_once './include/common.inc.php'; $keyWord=iconv('utf-8', 'gb2312', js_unescape($q)); $query = $db->query("SELECT DISTINCT(shopname) FROM {$dbpre}shops WHERE shopname LIKE '%$keyWord%' GROUP BY shopname ORDER BY addtime DESC LIMIT 0,10"); if($query) { while ($result = $db->fetch_array($query)) { echo $result['shopname']."\n"; } } //转换js escape提交过来数据 function js_unescape($str) { $ret = ''; $len = strlen($str); for ($i = 0; $i < $len; $i++) { if ($str[$i] == '%' && $str[$i+1] == 'u') { $val = hexdec(substr($str, $i+2, 4)); if ($val < 0x7f) $ret .= chr($val); else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f)); else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f)); $i += 5; } else if ($str[$i] == '%') { $ret .= urldecode(substr($str, $i, 3)); $i += 2; } else $ret .= $str[$i]; } return $ret; } ?>
附件如下:
http://xiazai.3water.com/200912/yuanma/jquery_autocomplete_php.rar
jquery自动完成插件(autocomplete)应用之PHP版
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@