频道直达 - 专题 - 新闻 - 技巧 - 组网 - 开发 - 安全 - web编程 - 图像 - 操作系统 - 数据库 - 教育 - 旅游 - 健康 - 时尚 - 驱动 - 软件 - 游戏 - 多媒体 - ERP - 讨论组

搜索自动提示功能的实现

来源: 作者:令狐葱 出处:巧巧读书 2008-03-13 进入讨论组

PHP后台程序(rpc.php):

如你所知(译注:不好意思,看王小波就学会了这么个口头禅),我的php后台程序都叫做rpc.php(RPC指远程过程调用),而没用它实际执行的功能来命名,但是也还不错了。

// PHP5 Implementation - uses MySQLi.
$db = new mysqli(‘localhost’, ‘root’ ,”, ‘autoComplete’);
if(!$db) {
    // Show error if we cannot connect.
    echo ‘ERROR: Could not connect to the database.’;
} else {
    // Is there a posted query string?
    if(isset($_POST[‘queryString’])) {
        $queryString = $_POST[‘queryString’];
        // Is the string length greater than 0?
        if(strlen($queryString) >0) {
        // Run the query: We use LIKE ‘$queryString%’
        // The percentage sign is a wild-card, in my example of countries it works like this…
        // $queryString = ‘Uni’;
        // Returned data = ‘United States, United Kindom’;
        $query = $db->query("SELECT value FROM countries WHERE value LIKE ‘$queryString%’ LIMIT 10");
        if($query) {
            // While there are results loop through them - fetching an Object (i like PHP5 btw!).
            while ($result = $query ->fetch_object()) {
                // Format the results, im using <li> for the list, you can change it.          
                // The onClick function fills the textbox with the result.
                echo ‘<li onclick="fill(’‘.$result->value.’‘);">’.$result->value.‘</li>’;
            }
        } else {
            echo ‘ERROR: There was a problem with the query.’;
        }
    } else {
        // Dont do anything.
    } // There is a queryString.
} else {
    echo ‘There should be no direct access to this script!’;
}
}

?>

PHP代码解释

鉴于代码中我已经加了很多注释,在这里我就不再说的很详细了。

一般情况下,需要接收这个 ‘QueryString’ 然后在其最后使用通配符产生一个查询语句。

这意味着在这种情况下,每次敲进去一个字符都需要产生一个查询语句,如果一直都这样做的话,恐怕MYSQL会受不了。但是为了尽量的简化这个过程,这种做法对一个规模较小的应用应该没什么问题。

这段php代码你需要在自己的系统中稍作修改,比如你需要更新‘$query’到你自己的数据库,需要看在哪里放你数据库表的列名等等。

CSS样式

我使用的是CSS3,天哪,它真的很好用,虽然在Firefox 或者Safari浏览器上会有功能限制。

<style type="text/css">
.suggestionsBox {
    position: relative;
    left: 30px;
    margin: 10px 0px 0px 0px;
    width: 200px;
    background-color: #212427;
    -moz-border-radius: 7px;
    -webkit-border-radius: 7px;
    border: 2px solid #000;
    color: #fff;
}

.suggestionList {
    margin: 0px;
    padding: 0px;
}

.suggestionList li {
    margin: 0px 0px 3px 0px;
    padding: 3px;
    cursor: pointer;
}

.suggestionList li:hover {
    background-color: #659CD8;
}
</style>

CSS代码都很标准,没什么需要特别指出的。

进入讨论组讨论。
收藏此文】【 】【打印】【关闭
较早的文章:Javascript风格要素 Ⅰ

较新的文章:通用滑动门类
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
巧巧读书宗旨
相关专题
讨论组问题推荐
站内各频道最新更新文档
站内最新制作专题
热门关键字导读
Photoshop教 程照片处理 照片制作 PS快捷键 抠图
计 算 机 故 障XP系统修复
艺 术 与 设 计设计 流媒体 设计欣赏 边框
计 算 机 安 全ARP
站内频道文章精选
巧巧电脑频道编辑信箱  告诉我们您想看的专题或文章