使用 jQuery(Ajax)/PHP/MySQL實現自動完成功能

JavaScript程式碼

<script src="jquery-1.2.1.pack.js" type="text/javascript"></script>
<script type="text/javascript">

function lookup(inputString) {
    if(inputString.length == 0) {
        // Hide the suggestion box.
        $(‘#suggestions’).hide();
    } else {
        $.post("rpc.php", {queryString: ""+inputString+""}, function(data){
            if(data.length >0) {
                $(‘#suggestions’).show();
                $(‘#autoSuggestionsList’).html(data);
            }
        });
    }
} // lookup

function fill(thisValue) {
    $(‘#inputString’).val(thisValue);
   $(‘#suggestions’).hide();
}

</script>

JS的解釋:

好,從上面的程式碼看到,我們需要連線到一個叫做rpc.php的檔案,這個檔案處理所有的操作。

lookup函式使用從文字輸入框中得到的單詞然後使用jQuery中Ajax的方法POST把它傳給rpc.php。

如果輸入字元 ‘inputString’是‘0’(Zero,譯註:在這裡是指在搜尋框中沒輸入任何內容),建議框就被隱藏,這也很人性化,你想,如果在搜尋框中沒有輸入任何東西,你也不期望會出現個建議提示框。

如果輸入框中有內容,我們就得到了這個 ‘inputString’並傳遞給rpc.php頁面,然後jQuery 的$.post()函式被使用,如下:

$.post(url, [data], [callback])

‘callback’部分可以關聯一個函式,這個比較有意思,只有在資料(data)被載入成功的時候才會執行(譯註:此處為意譯,沒看懂原文:<).

如果返回的資料(data)不為空(也就是說,有東西要顯示),那就顯示搜尋提示框並且使用返回的資料(data)來代替其中的html程式碼。

就這麼簡單!

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程式碼都很標準,沒什麼需要特別指出的。

主檔案HTML

程式碼

<div>
       <div>

      Type your county (for the demo):
<input size="30" id="inputString" onkeyup="lookup(this.value);" type="text" />

    </div>      <div class="suggestionsBox" id="suggestions" style="display: none;">

      <img src="upArrow.png" style="position: relative; top: -12px; left: 30px" alt="upArrow" />

      <div class="suggestionList" id="autoSuggestionsList">

</div>

    </div>

</div>

這是主檔案的部分html程式碼,你需要新增的就是一個輸入框,並且把 ‘onkeyup’ 函式設定為lookup(this.value)。另外,我建議你不要修改它的ID,如果你不想修改上面的Javascript程式碼的話。

截圖

我想你應該會想要看看最後的效果是什麼樣子,OK。

演示http://res.nodstrum.com/autoComplete/index.htm

轉自http://www.blueidea.com/tech/program/2008/5475_3.asp