使用bootstrap typeahead插件实现输入框自动补全之问题及解决办法
2016-07-25来源:易贤网

根据网上查找到的 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方法。

再回头现在的ace demo,虽然没有调用ajax的示例,但也有注释说明如何用,只不过用的是英文(题外话:做技术的懂英语真的很重要。),经过一翻调试,终于能正确显示了。贴出代码如下:

js代码

<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>

html

<!-- 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" />

以上所述是小编给大家介绍的使用bootstrap typeahead插件实现输入框自动补全之问题及解决办法,希望对大家有所帮助

2026公务员·事业单位培训课程试听报名

  • 报班类型
  • 姓名
  • 手机号
  • 验证码
推荐信息