用ASP實(shí)現(xiàn)搜索引擎的功能是一件很方便的事,可是,如何實(shí)現(xiàn)類似3721的智能搜索呢?比如,當(dāng)在搜索條件框內(nèi)輸入“中國人民”時(shí),自動(dòng)從中提取“中國”、“人民”等關(guān)鍵字并在數(shù)據(jù)庫內(nèi)進(jìn)行搜索。看完本文后,你就可以發(fā)現(xiàn),這個(gè)功能實(shí)現(xiàn)起來竟然是如此的簡單。
第一步,我們要建立一個(gè)名為db_sample.mdb的數(shù)據(jù)庫(本文以Access2000數(shù)據(jù)庫為例),并在其中建立表T_Sample。表T_Sample包括如下字段:
ID 自動(dòng)編號(hào)
U_Name 文本
U_Info 備注
第二步,我們開始設(shè)計(jì)搜索頁面Search.asp。該頁面包括一個(gè)表單(Frm_Search),表單內(nèi)包括一個(gè)文本框和一個(gè)提交按鈕。并將表單的method屬性設(shè)為“get” ,action屬性設(shè)為“Search.asp",即提交給網(wǎng)頁自身。代碼如下:
以下是代碼片段: <!-- Search.asp --> <form name="frm_Search" method="get" action="Search.asp"> 請輸入關(guān)鍵字: <input type="text" name="key" size="10"> <input type="submit" value="搜索"> </form> |
下面,就進(jìn)入了實(shí)現(xiàn)智能搜索的關(guān)鍵部分。
首先,建立數(shù)據(jù)庫連接。在Search.asp的開始處加入如下代碼:
以下是代碼片段: <% Dim strProvider,CNN strProvider="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" strProvider=strProvider & Server.MapPath("/") & "/data/db_Sample.mdb" 假設(shè)數(shù)據(jù)庫存放在主頁根目錄下的data目錄下 Set CNN = Server.CreateObject("ADODB.connection") CNN.Open strProvider 打開數(shù)據(jù)庫連接 %> |
接下來,判斷 ASP頁所接收到的數(shù)據(jù),并在數(shù)據(jù)庫中進(jìn)行搜索。
以下是代碼片段: <font color="#FF0000">未找到任何結(jié)果!!!</font> <% Else %> 搜索名稱為“<font color="#FF0000"><%= S_Key %></font>”的項(xiàng),共找到 <font color="#FF0000"><%= RST.RecordCount %></font> 項(xiàng):<p> <% While Not RST.EOF 遍歷整個(gè)記錄集,顯示搜索到的信息并設(shè)置鏈接 %> <!-- 此處可設(shè)為你所需要的鏈接目標(biāo) --> <font style="font: 12pt 宋體"><a href="info.asp?ID=<%= RST("ID") %>" target="_blank"><%= RST("U_Name") %></a></font> <!-- 顯示部分詳細(xì)內(nèi)容 --> <font style="font: 9pt 宋體"><%= Left(RST("U_Info"),150) %></font><p> <% RST.MoveNext Wend RST.Close Set RST=Nothing End If End If %> |
以下是代碼片段: <% Function AutoKey(strKey) CONST lngSubKey=2 Dim lngLenKey, strNew1, strNew2, i, strSubKey ’檢測字符串的合法性,若不合法則轉(zhuǎn)到出錯(cuò)頁。出錯(cuò)頁你可以根據(jù)需要進(jìn)行設(shè)定。 if InStr(strKey,"=")<>0 or InStr(strKey,"`")<>0 or InStr(strKey,"")<>0 or InStr(strKey," ")<>0 or InStr(strKey," ")<>0 or InStr(strKey,"")<>0 or InStr(strKey,chr(34))<>0 or InStr(strKey,"/")<>0 or InStr(strKey,",")<>0 or InStr(strKey,"<")<>0 or InStr(strKey,">")<>0 then Response.Redirect "error.htm" End If lngLenKey=Len(strKey) Select Case lngLenKey Case 0 若為空串,轉(zhuǎn)到出錯(cuò)頁 Response.Redirect "error.htm" Case 1 若長度為1,則不設(shè)任何值 strNew1="" strNew2="" ’Case Else 若長度大于1,則從字符串首字符開始,循環(huán)取長度為2的子字符串作為查詢條件 For i=1 To lngLenKey-(lngSubKey-1) strSubKey=Mid(strKey,i,lngSubKey) strNew1=strNew1 & " or U_Name like %" & strSubKey & "%" strNew2=strNew2 & " or U_Info like %" & strSubKey & "%" Next End Select ’得到完整的SQL語句 學(xué)習(xí)交流
熱門圖片
猜你喜歡的新聞
猜你喜歡的關(guān)注
新聞熱點(diǎn) 2024-04-27 13:35:46
2024-04-27 13:33:47
2024-04-24 22:53:44
2024-04-23 19:32:50
2024-04-23 19:25:50
2024-04-23 19:13:19
疑難解答 圖片精選 |