ENIX.DQ 發表於 2010-8-13 11:05:20

jQuery+AutoComplete與ASP

2013-06-03更新後記:


jQuery 官方已支援AutoComplete ( jQueryUI),可參考自:http://jqueryui.com/autocomplete/


本頁面提供之"jQueryAutoCompleteSample.Back.wDatabase.asp" 已不適用jQuery官方提供的AutoComplete

直接在ASP輸出JSON格式即可。


====================================
說明:
  本頁面將使用jQuery與plug-in AutoComplete並搭配ASP與MSSQL來完成在一input欄位中加入AutoComplete功能
此功能可在使用者於input欄位輸入資料的同時,顯示出建議的文字。

使用環境:
WebSevrer:IIS 7.5
資料庫:MS SQL 2005 Express Edition
測試瀏覽器:IE 8.0


網頁檔案:
1.jQueryAutoCompleteSample2.html - 主要操作頁面
2.jQueryAutoCompleteSample.Back.wDatabase.asp - 從DATABASE獲取資訊的ASP文件

嵌入之文件:
1.CSS檔-
2.AutoComplete JS檔
3.jQuery 1.4.2 min

1.在主要操作頁面嵌入這些檔案

<link type="text/css" rel="stylesheet" href="jquery.autocomplete.css"/>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery.autocomplete.min.js"></script>

2.input欄位設定,加入id標籤即可
<input name="Text1" type="text" id="t1"/>

3.在頁面加入下面這段代碼
   <script type="text/javascript">
       $("#t1").autocomplete(' jQueryAutoCompleteSample.Back.wDatabase.asp ');
    </script>

注意到,「#t1」其中t1的部分,就是input欄位的id名稱
「.autocomplete()」中包含的【jQueryAutoCompleteSample.Back.wDatabase.asp】 ,就是用來取得建議文字的功能網頁


4.【jQueryAutoCompleteSample.Back.wDatabase.asp】的輸出部分
只需注意輸出格式,由於AutoComplete處理原始資料時,是以斷行符號做為分割的依據
建議程式碼如下:

UserList = ""

If Not(rs.eof and rs.bof) then
While not(rs.eof)
UserList = UserList & rs("UserName") & vbcrlf
rs.movenext
Wend
End if

Response.write UserList


注意到第06行,ASP檔案在處理輸出字串時,每一筆資料的輸出
最後都帶有vbcrlf,這個vbcrlf在vbscript中代表的就是斷行字元
資料都處理完畢後,最後再進行資料的輸出,如此便可完成AutoComplete的所需要求


提醒的部分是,由於有開啟資料庫,請記得把開啟過的連線以.close關閉

如果要使用不連接資料庫的方法,請見參考資料連結


使用範例圖片:


參考資料:
1. Autocomplete - 自動完成文字輸入 - http://jsgears.com/thread-114-1-1.html
頁: [1]
查看完整版本: jQuery+AutoComplete與ASP