這就是貼代碼的壞處之一:搜索框快被網友玩兒壞了! ! !有故意輸入空格的,有輸入or 1=1的,有alert的,有html亂入的.......而且好像還在玩兒,隨他們去吧,只要開心就好。
在項目中,經常會用到輸入框的自動補全功能,就像百度、淘寶等搜索框一樣:當用戶輸入首字母、關鍵詞時,後台會迅速將與此相關的條目返回並顯示到前台,以便用戶選擇,提升用戶體驗。當然本項目的補全功能和這些大廠的技術是沒有可比性的,但用於站內搜索也是綽綽有餘了。
接觸到的自動補全插件主要有兩個:autocomplete和typeahead 。本站使用的是typeahead.
jQueryUI-Autocomplete
自動補全插件-bootstrap-3-typeahead
相關參數說明:
source: function(query,process){}。 query表示當前文本輸入框中的字符串,可在該方法中通過ajax向後台請求數據(數組形式的json對象),然後將返回的對像作為process的參數;
formatItem :function(item){}。對返回數據的具體某個json對象轉化為字符串格式,用以顯示在提示列表中,返回值:字符串;
setValue :function(item) {}。選中提示列表某項時,設置文本輸入框中顯示的值以及實際需要獲取的值。返回值格式:{'data-value':item["輸入框顯示值的item屬性"],'real-value':item["實際需要獲取值的item屬性"]},後期可通過文本輸入框的real-value屬性獲取該值;
items :自動完成提示的最大結果集數量,默認:8;
minLength:當前文本輸入框中字符串達到該屬性值時才進行匹配處理,默認:1;
delay :指定延時毫秒數後,才正真向後台請求數據,以防止輸入過快導致頻繁向後台請求,默認:500
具體代碼如下:
首先引入js文件
<script src="~/Scripts/jquery-1.9.0.js"></script> <script src="~/Scripts/bootstrap.js"></script> <script src="~/Content/js/bootstrap3-typeahead.js"></script>
Html代碼:
<form id="searchform" role="search" target="_blank" method="get" action="/Search/Index"><div><input type="text" id="searchWords" name="searchWords" data-provide="typeahead" autocomplete="off" placeholder="請輸入要搜索關鍵詞"></div><button type="submit" id="searchbtn">搜索</button></form>
處理相關搜索詞的js:
//搜索自動補全;給搜索框註冊自動聯想完成事件autoComplete: function () {jQuery('#searchWords').typeahead({source: function (query, process) {//query是輸入值jQuery.getJSON('/Search/GetHotSearchItems', { "query": query }, function (data) {process(data);});},updater: function (item) {return item.replace(/<a(.+?)<//a>/, ""); //這裡一定要return,否則選中不顯示},afterSelect: function (item) {//選擇項之後的時間,item是當前選中的項alert(item);},items: 8, //顯示8條delay: 500 //延遲時間});},後台處理/Search/GetHotSearchItems:
#region 2.0 jquery typeahead插件異步獲取搜索熱詞、自動補全搜索框; ActionResult GetHotSearchItems()/// <summary>/// 2.0 jquery typeahead插件異步獲取搜索熱詞、自動補全搜索框>/// 每搜索一次就將此次用戶搜索的詳情入庫>/// 定時任務每隔10分鐘統計一次各搜索詞的次數、將統計信息更新到SearchRank表/// </summary>/// <returns>JSON</returns>public ActionResult GetHotSearchItems(){//2.1 先獲取當前搜索詞"query"string query = Request["query"];//2.2 從數據庫中查詢此字段的熱詞集合IBLL.ISearchRankService hotService = OperateHelper.Current.serviceSession.SearchRankService;//2.3 從數據庫中檢索出包含此搜索詞的熱詞集合,並按搜索次數排序,將數據返回給typeahead.jsList<SearchRank> hotList = hotService.GetDataListBy(s => s.KeyWord.Contains(query), s => s.SearchTimes);if (hotList != null){var list1 = hotList.Select(h => new{name = h.KeyWord,times = h.SearchTimes}).ToList();ArrayList list2 = new ArrayList();int i = 1;foreach (var item in list1){list2.Add(string.Format("<a class=/"cat/" href=/"#/">{0}</a>{1}", i, item.name));i++;}return Json(list2, JsonRequestBehavior.AllowGet);}else{return Json("", JsonRequestBehavior.AllowGet);}} #endregion就先這樣吧。