首页 > 解决方案 > 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.logoutputsuccess我的 ajax 中得到以下信息时;

success:function(output){
    console.log(output);        
    return output;
}

在此处输入图像描述

标签: javascriptarraysajaxtypeahead.js

解决方案


我通过延迟我的 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
        )
    }); 
});

推荐阅读