我跟着typeahead documentation example: The Basics。当我从'The Basics'复制/粘贴示例代码时,它工作正常。我改变的是我做了一个ajax请求代替那个静态数组。
代码:
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
/* only part I really changed */
/* I replaced the static array from the example */
/* with an array I am getting from ajax request. */
var agencies_ary = []
$.ajax({
url: "agencies/get_unique_agency_names",
type: "GET",
success: function(data){
agencies_ary = data;
}
})
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'agencies_ary',
source: substringMatcher(agencies_ary)
});
ajax请求有效。它正确返回一个名称数组。
答案 0 :(得分:0)
我将展示两种不同的解决方案。两者都有效。一个比另一个短很多。
解决方案1 :
var agency_names = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'agencies/get_unique_agency_names'
});
$('.typeahead.name_input').typeahed(null, {
name: 'agency_names',
source: agency_names
});
解决方案2
我在原始问题中对代码的问题是在发送ajax请求之前加载了javascript。要在javascript之前执行ajax请求,我只需在.done
中指定javascript:
var agencies_ary = [];
$.ajax({
url: "agencies/get_unique_agency_names",
type: "GET",
success: function(data){
agencies_ary = data;
console.log(agencies_ary[0]);
}
}).done(function(){
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'agencies_ary',
source: substringMatcher(agencies_ary)
});
});
答案 1 :(得分:0)
等待ajax调用完成然后设置typeahead的解决方案是一种方法来做到这一点并祝贺它工作:),但IMO更简单,更快速地使用typeahead进行调用,例如:
$('.typeahead').typeahead({
remote: { url: "agencies/get_unique_agency_names" }
})