【发布时间】:2011-08-20 06:52:05
【问题描述】:
我正在尝试将每个 Ajax 自动完成结果与特定 URL(“登陆页面”)链接起来。
网址:www.aebli.com,右上角搜索栏,用“h”或“ho”试试
搜索框的 Ajax 代码:
<script type="text/javascript" src="js/dimensions.js"></script>
<script type="text/javascript" src="js/autocomplete.js"></script>
<script type="text/javascript">
$(function(){
setAutoComplete("searchField", "results", "php/autocomplete.php?part=");
});
</script>
这里是“autocomplete.php”文件,它从 MySQL 数据库中选择特定的表:
<?php
$link = mysql_connect('localhost', 'root', 'root');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db("dreampix")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$result = mysql_query("SELECT name FROM treffer");
while ($row = mysql_fetch_assoc($result)) {
$colors[]=$row['name'];
}
mysql_free_result($result);
mysql_close($link);
// check the parameter
if(isset($_GET['part']) and $_GET['part'] != '')
{
// initialize the results array
$results = array();
// search colors
foreach($colors as $color)
{
// if it starts with 'part' add to results
if( strpos($color, $_GET['part']) === 0 ){
$results[] = $color;
}
}
// return the array as json with PHP 5.2
echo json_encode($results);
}
?>
正如您在www.aebli.com 上看到的,搜索字段有效,请尝试使用“ho”。 MySQL-Database-Table 仅包含两行:id 和一些条目,如“hochzeit”。如何将带有<a href="#"> 的 AJAX 自动完成结果“连接”到特定的登录页面,例如“hochzeit”.php 的 aebli.com/searchresluts?
我希望用户搜索“ho”,得到一个列表,然后可以点击其中一个结果来打开目标网页。..
【问题讨论】:
-
您应该在 SQL 查询中使用 WHERE 子句过滤结果。它比在 PHP 中选择所有行并手动过滤它们要快。 (但要注意 SQL 注入)
标签: php mysql ajax json autocomplete