【发布时间】:2019-08-04 00:51:01
【问题描述】:
我正在使用 twitter typeahead javascript 库来预填充搜索词,以帮助用户搜索特定名称。我正在使用他们的示例 substringMatcher 函数,该函数可以在 here 中找到。
我正在使用 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 来自我的 ajax 的 success 时,我得到以下信息;
success:function(output){
console.log(output);
return output;
}
【问题讨论】:
-
Ajax 调用是异步的,您不应从 ajax 调用的“成功”函数返回值。相反,您可以使用promise 来监控Ajax 调用的完成情况,然后使用promise 的“then”方法做进一步的工作。
-
请提供您的 ajax 调用输出。根据
substringMatcher文档,它需要字符串数组。 -
@Sagar 谢谢,更新了 ajax 调用的结果集
-
那么数据格式就没有问题了。考虑@RK_15 评论。
-
@RK_15 谢谢,我刚刚硬编码了一个数组变量,结果输出按预期工作!请您进一步解释您的建议。谢谢
标签: javascript arrays ajax typeahead.js