日期:2014-05-16  浏览次数:20691 次

jquery/autocomplete/php/mysql搜索自动完成

                              本示例根据jquery插件autocomplete的demo修改
1.下载php autocomplete插件
2.建立php项目,取名为autocompleteTest
示例结构如下:

3.将插件示例里面的jquery.autocomplete.css,jquery.autocomplete.js,jquery-1.4.2.js复制到项目的目录下。
4.建立html文件:index.html
代码如下:
<html>
<head>
<title>jQuery Autocomplete demo</title>
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#singleBirdRemote").autocomplete("search.php", {
width: 300,
selectFirst: false
});
$("#singleBirdRemote").result(function(event, data, formatted) {
if (data)
$(this).parent().next().find("input").val(data[1]);
});
});
</script>
</head>
<body><input type="text" id="singleBirdRemote" /><input />
</body>
</html>


5.建立和html文件同一目录下的php文件:search.php
代码如下:
<?php
 header("content-type:text/html; charset=utf-8");
$q = strtolower($_GET["q"]);
if (!$q) return;
$conn = @mysql_connect ( "localhost", "root", "" ); //连接数据库 
mysql_query("SET NAMES 'utf8'");//处理乱码     
//mysql_query ( "SET character_set_connection=gbk , character_set_results=gbk, character_set_client=gbk, sql_mode='' " );
mysql_select_db ( "demo", $conn ); //选择数据库      
$array ;
if ($conn) {
$recode = "select * from fc_subdistrict";
$result = mysql_query ( $recode, $conn );
while ( $row = mysql_fetch_array ( $result, MYSQL_ASSOC ) ) {
$array [$row ['name']] = $row ["id"];
}
}
foreach ($array as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
echo "$key|$value\n";
}}
?>

代码就这么多,就这么简单,我也是刚刚才学,希望高手看了之后觉得写的不好,请指出!