javascript - Typeahead 结果填充返回整个数组对象
问题描述
我正在使用 twitter typeahead javascript 库来预填充搜索词,以帮助用户搜索特定名称。我正在使用他们的示例substringMatcher
函数,可以在这里找到。
我正在使用 Ajax 调用填充我的数据,该调用返回我期望的数据。然后将该数组传递给该示例substringMatcher
函数,但是在搜索时它返回整个数组而不是每个单独的项目(见图)。
它应该只返回个人名称,而不是数组!
他是我的预输入功能和来源;
$('input#practition-typeahead').typeahead({
hint: true,
highlight: true,
minLength: 3,
},{
name: 'output',
source: substringMatcher(
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
dataType: "json",
data: {
action: 'get_all_practitioners'
},
success:function(output){
return output;
}
})
)
});
我的子字符串匹配器功能
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
编辑 -
当console.log
我output
从success
我的 ajax 中得到以下信息时;
success:function(output){
console.log(output);
return output;
}
解决方案
我通过延迟我的 typeahead 实例直到 ajax 调用完成来解决了这个问题。完整的代码可以在下面找到;
var output = [];
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
dataType: "json",
data: {
action: 'get_all_practitioners'
},
success:function(output){
console.log(output);
return output;
}
}).done(function(output){
$('input#practition-typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1,
},{
name: 'output',
source: substringMatcher(
output
)
});
});
推荐阅读
- laravel - Laravel 使用无条件查找和动态 where 条件
- c# - 在 Azure Function 中覆盖 function.json 的问题
- android - 如何处理父视图上的触摸事件?
- java - 如何使用片段和顶点着色器使 2D 纹理表面不均匀?从纹理中删除某些像素?
- javascript - 为什么喜欢和不喜欢不能正常工作
- string - 打印两个字符串中相同且出现在相同位置的字符数
- sequelize.js - Sequelize 将 2 个查询组合为 sub where
- javascript - 提高计算两点之间距离的性能
- javascript - 0 谷歌脚本中谷歌表格中的前导数字格式
- javascript - npm update 不更新所有过时的模块