站內搜尋

Wednesday, December 26, 2012

[jQuery] 簡單做出像google搜尋一樣的自動完成效果 (jQuery UI Autocomplete)

1.引入jquery的程式

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

2.js主程式

<script>
  $(function() {
    $('#auto').autocomplete({
      source: "ajax.php",
      minLength: 3
    });
  });
</script>

3.html碼
<input type="text" id="auto" />

說明:
1.預設的變數名稱是"term",所以接收頁要用$_GET["term"]來接值。
2.ajax.php輸出的格式"必須"是json。
範例如下:

$sql = "select * from table where name like '".$_GET['term']."%'";
$query=$db->query($sql);
while($result=$db->fetch_array($query)){
$rows[] = $result['name'];
}
echo json_encode($rows);

註1:
minLength: 3 代表至少要輸入三碼才啟動自動完成,如果Server主機效能很好,可以改成1。其他參數的中文說明可參考 這裡 

註2:
可將 source 改為一個標準ajax函式
source: function(request, response) {
    // 使用標準的 jQuery $.ajax 方法
    $.ajax({
        url: "search_api.php", // API 的基本 URL
        dataType: "json", // 使用 data 屬性來傳遞所有參數
        data: {
            act: "auto", // 您固定的參數
            term: request.term // 使用者輸入的關鍵字
        },
        success: function(data) {
            // 成功後,呼叫 response() 並將回傳的資料傳入
            // Autocomplete 元件會自動處理剩下的事 
            response(data);
        },
        error: function() {
            // 錯誤處理 (可選) response([]); // 發生錯誤時回傳空陣列
        }
     });
 },

No comments:

Post a Comment