Typeahead结果填充返回整个数组对象

问题描述 投票:4回答:1

我正在使用twitter typeahead javascript库预先填充搜索词,以帮助用户搜索特定名称。我正在使用他们的示例substringMatcher函数,可以找到here

我正在使用Ajax调用填充我的数据,该调用返回我期望的数据。然后将此数组传递给该示例substringMatcher函数,但是在搜索时它返回整个数组而不是每个单独的项目(请参见图像)。

它应该只返回个人名称,而不是数组!

enter image description here

在这里,他是我的先行功能和来源;

$('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);
  }; 
};

编辑 - 当我从我的ajax的console.log output我的success时,我得到以下内容;

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

enter image description here

javascript arrays ajax typeahead.js
1个回答
2
投票

我已经通过延迟我的预先输出实例来解决这个问题,直到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
        )
    }); 
});
© www.soinside.com 2019 - 2024. All rights reserved.