DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
仿 Google Suggest:PHP + Prototype 實作搜尋建議下拉
編輯:AJAX詳解     

本文示範如何以 PHP、MySQL 搭配 Prototype 函式庫,實作出類似 Google Suggest 的搜尋建議功能,包含鍵盤上下鍵選擇、滑鼠移入高亮與點擊帶入等完整互動。

一、建立資料表

CREATE TABLE `suggest` (
  `id`    INT NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(100) NOT NULL,
  `hits`  INT NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE = InnoDB;

insert into suggest(title, hits) values('xqbar.com', 100);
insert into suggest(title, hits) values('www.xqbar.com', 410);
insert into suggest(title, hits) values('https://xqbar.com', 700);
insert into suggest(title, hits) values('mail:xqbar.com', 200);
insert into suggest(title, hits) values('FTP:xqbar.com', 100);
insert into suggest(title, hits) values('https://www.xqbar.com', 70);

二、後端查詢 search.php

回傳的字串格式約定為 結果1|結果2$點擊數1|點擊數2,兩段以 $ 分隔且前後順序對應:

<?php
if ($_GET["action"] != '') {
    # 取得使用者輸入的關鍵字
    $keyWord = $_GET["keyWord"];

    # 過濾 like 語句中的特殊字元
    $keyWord = str_replace("[", "[[]", $keyWord);
    $keyWord = str_replace("&", "[&]", $keyWord);
    $keyWord = str_replace("%", "[%]", $keyWord);
    $keyWord = str_replace("^", "[^]", $keyWord);

    $conn = mysql_connect("localhost", "xqbar", "xqbaradmin");
    @mysql_select_db("xqbar") or die('sorry');
    mysql_query('set names utf-8');

    $sql = "select title, hits from suggest
            where title like '%" . $keyWord . "%'
            order by hits desc limit 10";
    $result = mysql_query($sql);

    if ($result) {
        $i = 1; $title = ''; $hits = '';
        while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
            $title .= $row['title'];
            $hits  .= $row['hits'];
            if ($i < mysql_num_rows($result)) {
                $title .= "|";
                $hits  .= "|";
            }
            $i++;
        }
    }
    mysql_close();
}
?>
<?php echo $title . '$' . $hits; ?>

三、引入 Prototype

有朋友反映這個函式庫體積偏大,不習慣的人可以改用 jQuery,或直接自行建立 Ajax 物件。此處沿用 Prototype 寫法:

<script type="text/javascript" src="prototype.js"</script>

四、提示層與互動邏輯

<script type="text/javascript">
// lastindex 記錄滑鼠目前所在的位置,初始為 -1
var lastindex = -1;
// flag 表示是否允許根據輸入內容發送 Ajax 查詢
var flag = false;
// 回傳結果所生成的項目數
var listlength = 0;

// 自訂字串緩衝類別,減少大量拼接時的字串物件配置
function StringBuffer() { this.data = []; }
StringBuffer.prototype.append = function () {
    this.data.push(arguments[0]);
    return this;
};
StringBuffer.prototype.tostring = function () {
    return this.data.join("");
};

// 去除字串兩端空白
String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};

// 隱藏提示層與 iframe
function hiddensearch() {
    $('rlist').style.display = "none";
    $('rFrame').style.display = "none";
}

// 顯示提示層與 iframe,num 為項目數
function showsearch(num) {
    $('rlist').style.display = '';
    $('rFrame').style.display = '';
    // 每項高度 20px,加上 padding 的 1px
    $('rlist').style.height  = num * 20 + num + 'px';
    $('rFrame').style.height = num * 20 + num + 'px';
}

// 取得元素距離視窗左上角的絕對位置
function getposition(element, offset) {
    var c = 0;
    while (element) {
        c += element[offset];
        element = element.offsetParent;
    }
    return c;
}

// 建立提示層與 iframe
// iframe 的作用是墊在 select 之上,避免舊版 IE 中下拉選單穿透提示層
function createlist() {
    var listDiv = document.createElement("div");
    listDiv.id = "rlist";
    listDiv.style.zIndex = "2";
    listDiv.style.position = "absolute";
    listDiv.style.border = "solid 1px #000000";
    listDiv.style.backgroundColor = "#FFFFFF";
    listDiv.style.display = "none";
    listDiv.style.width = $('keyWord').clientWidth + "px";
    listDiv.style.left = getposition($('keyWord'), 'offsetLeft') + 1.5 + "px";
    listDiv.style.top = (getposition($('keyWord'), 'offsetTop') +
                         $('keyWord').clientHeight + 3) + "px";

    var listFrame = document.createElement("iframe");
    listFrame.id = "rFrame";
    listFrame.style.zIndex = "1";
    listFrame.style.position = "absolute";
    listFrame.style.border = "0";
    listFrame.style.display = "none";
    listFrame.style.width = $('keyWord').clientWidth + "px";
    listFrame.style.left = getposition($('keyWord'), 'offsetLeft') + 1 + "px";
    listFrame.style.top = (getposition($('keyWord'), 'offsetTop') +
                           $('keyWord').clientHeight + 3) + "px";

    document.body.appendChild(listDiv);
    document.body.appendChild(listFrame);
}

function setstyle(element, classname) {
    switch (classname) {
        case 'm':   // 滑鼠移入/鍵盤選中
            element.style.fontSize = "12px";
            element.style.fontFamily = "arial,sans-serif";
            element.style.backgroundColor = "#3366cc";
            element.style.color = "black";
            element.style.width = $('keyWord').clientWidth - 2 + "px";
            element.style.height = "20px";
            element.style.padding = "1px 0px 0px 2px";
            if (element.displaySpan) element.displaySpan.style.color = "white";
            break;
        case 'd':   // 一般狀態
            element.style.fontSize = "12px";
            element.style.fontFamily = "arial,sans-serif";
            element.style.backgroundColor = "white";
            element.style.color = "black";
            element.style.width = $('keyWord').clientWidth - 2 + "px";
            element.style.height = "20px";
            element.style.padding = "1px 0px 0px 2px";
            if (element.displaySpan) element.displaySpan.style.color = "green";
            break;
        case 't':   // 左側標題欄
            element.style.width = "80%";
            if (window.navigator.userAgent.toLowerCase().indexOf("firefox") != -1)
                element.style.cssFloat = "left";
            else
                element.style.styleFloat = "left";
            element.style.whiteSpace = "nowrap";
            element.style.overflow = "hidden";
            element.style.textOverflow = "ellipsis";
            element.style.fontSize = "12px";
            element.style.textAlign = "left";
            break;
        case 'h':   // 右側點擊數欄
            element.style.width = "20%";
            if (window.navigator.userAgent.toLowerCase().indexOf("firefox") != -1)
                element.style.cssFloat = "right";
            else
                element.style.styleFloat = "right";
            element.style.textAlign = "right";
            element.style.color = "green";
            break;
    }
}

function focusitem(index) {
    if ($('item' + lastindex) != null) setstyle($('item' + lastindex), 'd');
    if ($('item' + index) != null) {
        setstyle($('item' + index), 'm');
        lastindex = index;
    } else {
        $("keyWord").focus();
    }
}

function searchclick(index) {
    $("keyWord").value = $('title' + index).innerHTML;
    flag = true;
}

function searchkeydown(e) {
    if ($('rlist').innerHTML == '') return;

    var keycode = (window.navigator.appName == "Microsoft Internet Explorer")
                  ? event.keyCode : e.which;

    if (keycode == 40) {          // 向下
        if (lastindex == -1 || lastindex == listlength - 1) {
            focusitem(0); searchclick(0);
        } else {
            focusitem(lastindex + 1); searchclick(lastindex + 1);
        }
    }
    if (keycode == 38) {          // 向上
        if (lastindex == -1) {
            focusitem(0); searchclick(0);
        } else {
            focusitem(lastindex - 1); searchclick(lastindex - 1);
        }
    }
    if (keycode == 13) {          // 實行
        focusitem(lastindex);
        $("keyWord").value = $('title' + lastindex).innerText;
    }
    if (keycode == 46 || keycode == 8) {
        flag = false;
        Ajaxsearch($F('keyWord').substring(0, $F('keyWord').length - 1).Trim());
    }
}

function showresult(XMLhttp) {
    var result = unescape(XMLhttp.responseText);
    if (result != '') {
        var resultstring = new StringBuffer();
        var title = result.split('$')[0];
        var hits  = result.split('$')[1];

        for (var i = 0; i < title.split('|').length; i++) {
            resultstring.append('<div id="item' + i + '" onmousemove="focusitem(' + i +
                                ')" onmousedown="searchclick(' + i + ')">');
            resultstring.append('<span id=title' + i + '>');
            resultstring.append(title.split('|'));
            resultstring.append('</span>');
            resultstring.append('<span id=hits' + i + '>');
            resultstring.append(hits.split('|'));
            resultstring.append('</span></div>');
        }

        $('rlist').innerHTML = resultstring.tostring();

        for (var j = 0; j < title.split('|').length; j++) {
            setstyle($('item' + j), 'd');
            $('item' + j).displaySpan = $('hits' + j);
            setstyle($('title' + j), 't');
            setstyle($('hits' + j), 'h');
        }

        showsearch(title.split('|').length);
        listlength = title.split('|').length;
        lastindex = -1;
    } else {
        hiddensearch();
    }
}

function Ajaxsearch(value) {
    new Ajax.Request('search.php', {
        method: "get",
        parameters: "action=do&keyWord=" + escape(value),
        onComplete: showresult
    });
}

function main() {
    $('keyWord').className = $('keyWord').className == 'inputblue'
                             ? 'inputfocus' : 'inputblue';
    if ($F('keyWord').Trim() == '') {
        hiddensearch();
    } else {
        if ($F('keyWord') != '' && flag == false)
            Ajaxsearch($F('keyWord').Trim());
        if (listlength != 0) $('keyWord').onkeydown = searchkeydown;
        else hiddensearch();
    }
}

function oninit() {
    $('keyWord').autocomplete = "off";
    $('keyWord').onfocus = main;
    $('keyWord').onkeyup = main;
    $('keyWord').onblur = hiddensearch;
    createlist();
}

Event.observe(window, 'load', oninit);
</script>

五、搜尋框的 HTML

<form id="form1" name="form1" method="post" action="">
    <b>輸入搜索關鍵字</b>
    <input name="keyWord" type="text" class="inputblue"
           id="keyWord" maxlength="20" style="width:300px;" />
</form>

實作提醒

這個範例寫於 Prototype 與 mysql_* 函式仍是主流的年代,有幾處在今日必須修正:mysql_* 系列函式已被移除,請改用 PDO 或 MySQLi 並搭配參數化查詢;提示內容輸出到 innerHTML 前應做 HTML 編碼,否則使用者輸入的內容會成為 XSS 的入口;此外 iframe 墊層是為了繞過舊版 IE 的 select 穿透問題,現代瀏覽器已無此困擾,可直接移除。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved