照著網路上的教學接好 Bootstrap typeahead,資料庫的資料確實讀得出來,打斷點也看得到回傳的內容,但輸入框下方的建議清單卻全部顯示成 undefined。反覆檢查半天,看不出哪裡寫錯。
答案藏在一句很容易掃過去的說明:「在當前版本的 typeahead 中,已經不再支持在 source 屬性中直接調用 ajax 方法獲取數據源了。」
舊版教學普遍把 ajax 呼叫直接寫在 source 裡,而新版把 source 改成「函數工廠」的形式——source 必須是一個回傳函數的函數,資料請求要在被回傳的那個函數裡進行。寫法沒跟上,就會拿到 undefined。
更根本的一點是:typeahead 期望的建議項目是物件,且必須透過 displayKey 指定要顯示哪個屬性。若 process 收到的是一堆純字串陣列而 displayKey 又指向不存在的屬性,一樣會顯示 undefined。
<script type="text/javascript"> jQuery(function($) { //typeahead.js //example taken from plugin's page at: https://twitter.github.io/typeahead.js/examples/ var substringMatcher = function() {//substringMatcher()方法 return function findMatches(query, process) {//query 是配備的關鍵字,processj是返回的值 var matches, substringRegex; var params = {"token": getStorage("token"), "flag":0,"name":query}; var parameter_str=""; for(var key in params){ parameter_str+="&"+key+"="+params[key]; } var fullurl=getOption("gykj_host")+"institution/list?"+getOption("gykj_callbackparam")+"="+getOption("gykj_callbackfunc")+parameter_str; $("#submenu_info").html(fullurl); $.ajax({ url:fullurl, type:'get', dataType:"jsonp", jsonp:getOption("gykj_callbackparam"), jsonpCallback:getOption("gykj_callbackfunc"), async:false, error:function(){ alert("列表:"+getOption("connectionErrorMessage")); }, success:function(data){ //$("#submenu_info").html(fullurl); if(data.code==0){ var arr,substringRegex; arr=[]; substrRegex = new RegExp(query);//這必須有,要不還是顯示為underfined for(var item in data.data){ var str= data.data[item].name; if (substrRegex.test(str)) { // the typeahead jQuery plugin expects suggestions to a // JavaScript object, refer to typeahead docs for more info arr.push({ value:str}); } } process(arr); } } }) } } $('input.typeahead').typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'states', displayKey: 'value', source: substringMatcher()//當前版本source屬性中不能直接調用ajax方法獲取數據源,通過substringMatcher()方法 }); }); </script>
<!-- inline scripts related to this page --> <script src="../assets/js/ace-elements.js"></script> <script src="../assets/js/typeahead.jquery.js"></script> <input type="text" id="name" placeholder="機構名稱" class="col-xs-10 col-sm-5 typeahead scrollable" value="" autocomplete="off" />
source 是函數工廠。substringMatcher() 這個立即呼叫回傳了內部的 findMatches 函數,typeahead 拿到的是 findMatches。這正是新版要求的結構。
推入的是物件而非字串。arr.push({ value: str }) 搭配 displayKey: 'value',兩者必須成對出現。少了 displayKey,typeahead 不知道該顯示物件的哪個屬性,就會印出 undefined。
substrRegex 這行不能省。程式碼註解也特別標了。它是用來過濾後端回傳的結果,只保留符合查詢關鍵字的項目。若後端已做過篩選,這行可以移除;但要注意 new RegExp(query) 直接吃使用者輸入,當輸入包含 (、*、? 這類字元時會拋出語法錯誤,應該先做跳脫處理。
async: false 應該避免。同步的 AJAX 會凍結整個瀏覽器 UI,使用者在請求等待期間無法輸入、捲動或點擊。typeahead 是非同步元件,process 回呼的設計本來就是為了非同步流程,這裡沒理由犧牲它。
type:'get' 的字串拼寫。jQuery 接受 'get',但慣例寫小寫 'GET' 或直接省略 type(預設即 GET)。這不影響功能,只是可讀性問題。
$('input.typeahead').typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'institution', displayKey: 'value', source: function findMatches(query, process) { $.ajax({ url: getOption('gykj_host') + 'institution/list', data: { name: query, flag: 0 }, dataType: 'jsonp', success: function (data) { if (data.code !== 0) { process([]); return; } process(data.data.map(function (item) { return { value: item.name }; })); }, error: function () { process([]); } }); } });
這裡用 data 物件讓 jQuery 自己組查詢字串,避免手工拼接帶來的編碼問題;用 map 取代 for-in 迴圈,語意更清楚(for-in 會枚舉原型鏈上的屬性,處理陣列時並不建議);error 時呼叫 process([]) 清空建議,比彈 alert 打斷使用者好得多。
補充一點:typeahead.js 已多年未更新,若為新專案,可考慮 bootstrap-3-typeahead 這類仍在維護的分支,或直接用 HTML5 <datalist> 處理簡單場景。