使用bootstrap typeahead插件实现输入框自动补全之问题及解决办法
根据网上查找到的typeahead使用方法,到最后一步时就出错,数据能从数据库读取出来,但在输入框显示提示时,全都显为:underfined。捉摸了半天都发现不了问题出在哪儿。后来在http://blog.64cm.com/post/2014/08/13/%E4%BD%BF%E7%94%A8bootstrap-typeahead%E6%8F%92%E4%BB%B6上不经意发现这么一句话:“在当前版本的typeahead中,已经不再支持在source属性中直接调用ajax方法获取数据源了。”提醒了我,因为我根据网上的方法,是直接在source中调用ajax方法。
再回头现在的acedemo,虽然没有调用ajax的示例,但也有注释说明如何用,只不过用的是英文(题外话:做技术的懂英语真的很重要。),经过一翻调试,终于能正确显示了。贴出代码如下:
js代码
<scripttype="text/javascript">
jQuery(function($){
//typeahead.js
//exampletakenfromplugin'spageat:https://twitter.github.io/typeahead.js/examples/
varsubstringMatcher=function(){//substringMatcher()方法
returnfunctionfindMatches(query,process){//query是配备的关键字,processj是返回的值
varmatches,substringRegex;
varparams={"token":getStorage("token"),"flag":0,"name":query};
varparameter_str="";
for(varkeyinparams){
parameter_str+="&"+key+"="+params[key];
}
varfullurl=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){
vararr,substringRegex;
arr=[];
substrRegex=newRegExp(query);//这必须有,要不还是显示为underfined
for(varitemindata.data){
varstr=data.data[item].name;
if(substrRegex.test(str)){
//thetypeaheadjQuerypluginexpectssuggestionstoa
//JavaScriptobject,refertotypeaheaddocsformoreinfo
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>
html
<!--inlinescriptsrelatedtothispage--> <scriptsrc="../assets/js/ace-elements.js"></script> <scriptsrc="../assets/js/typeahead.jquery.js"></script> <inputtype="text"id="name"placeholder="机构名称"class="col-xs-10col-sm-5typeaheadscrollable"value=""autocomplete="off"/>
以上所述是小编给大家介绍的使用bootstraptypeahead插件实现输入框自动补全之问题及解决办法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!