DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
用jQuery、AJAX、PHP與MySQL實作自動完成功能
編輯:AJAX詳解     

本文示範如何打造類似搜尋框的「自動完成」提示:使用者輸入時,即時從資料庫比對並列出建議項目,點擊即可填入。

前端 JavaScript

<script src="jquery-1.2.1.pack.js" type="text/javascript"></script>
<script type="text/javascript">
function lookup(inputString) {
  if(inputString.length == 0) {
    $('#suggestions').hide(); // 輸入為空則隱藏建議框
  } else {
    $.post("rpc.php", {queryString: ""+inputString+""}, function(data){
      if(data.length > 0) {
        $('#suggestions').show();
        $('#autoSuggestionsList').html(data);
      }
    });
  }
}
function fill(thisValue) {
  $('#inputString').val(thisValue);
  $('#suggestions').hide();
}
</script>

lookup() 取得輸入框中的字串,以 jQuery 的 $.post() 傳給 rpc.php。若輸入為空就隱藏建議框,避免無意義的提示;若有內容則把回傳資料填入建議清單。$.post(url, [data], [callback]) 的 callback 只有在資料載入成功時才執行。

後端 PHP(rpc.php)

<?php
// PHP5 實作,使用 MySQLi
$db = new MySQLi('localhost', 'root', '', 'autoComplete');
if(!$db) {
  echo 'ERROR: Could not connect to the database.';
} else {
  if(isset($_POST['queryString'])) {
    $queryString = $_POST['queryString'];
    if(strlen($queryString) > 0) {
      // 使用 LIKE '查詢字%' 做前綴比對,% 為萬用字元
      $query = $db->query("SELECT value FROM countries
        WHERE value LIKE '$queryString%' LIMIT 10");
      if($query) {
        while ($result = $query->fetch_object()) {
          echo '<li onclick="fill('.$result->value.');">'.$result->value.'</li>';
        }
      } else {
        echo 'ERROR: There was a problem with the query.';
      }
    }
  } else {
    echo 'There should be no direct access to this script!';
  }
}
?>

後端接收 queryString 並以萬用字元組出查詢,每輸一個字就查一次;對小型應用沒問題,正式環境建議加上輸入過濾與參數化查詢以防 SQL injection。

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; }

主頁面 HTML

主頁只需一個輸入框,把 onkeyup 設為 lookup(this.value),並準備好建議框與清單容器:

<div>
  <div>Type your country:
    <input size="30" id="inputString" onkeyup="lookup(this.value);" type="text" />
  </div>
  <div class="suggestionsBox" id="suggestions" style="display: none;">
    <div class="suggestionList" id="autoSuggestionsList"></div>
  </div>
</div>

只要保留 suggestion 相關的 id 對應,即可 reuse 這套自動完成邏輯到你的專案。

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