TypeAhead和Bloodhound只搜索JSON数组中的第一个单词



我使用TypeAhead为文本框提供自动完成结果。但似乎无论是Bloodhound还是TypeAhead都只搜索在我提供的JSON数组中找到的第一个单词。

JSON如下所示:

[
    {
        "name": "ALICE",
        "value": "ALICE",
        "physical_address": "ERF 270 CNR. OF THOMPSON AND INTWANA STREET, ALICE",
        "province": "PROVINCE",
        "tokens": [
            "ALICE",
            "PROVINCE",
            "ERF",
            "270",
            "CNR.",
            "OF",
            "THOMPSON",
            "AND",
            "INTWANA",
            "STREET",
            "ALICE"
        ]
    },
    {
        "name": "BUTTERWORTH",
        "value": "BUTTERWORTH",
        "physical_address": "SHOP NO. 1 MASONIC SHOPPING COMP, COR HIGH & BELL STREET BUTTERWORTH 4960",
        "province": "PROVINCE",
        "tokens": [
            "BUTTERWORTH",
            "PROVINCE",
            "SHOP",
            "NO.",
            "1",
            "MASONIC",
            "SHOPPING",
            "COMP",
            "COR",
            "HIGH",
            "&",
            "BELL",
            "STREET",
            "BUTTERWORTH",
            "4960"
        ]
    }
]

我将按如下方式初始化TypeAhead:

HTML:

<div class="films">
    <input type="text" class="form-control typeahead" placeholder="Search" name="films" autocomplete="off" id="search">
</div>
Javascript:

/* TypeAhead invoked */
var _prefetch_url = $root_path + '/media/mod_storelocator/stores_json.php';
// constructs the suggestion engine
var films = new Bloodhound({
    datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 15,
    prefetch: _prefetch_url
});
// kicks off the loading/processing of `local` and `prefetch`
films.initialize();
$('.films .typeahead').typeahead(null, {
    displayKey : 'value',
    source: films.ttAdapter(),
    templates: {
        suggestion: Handlebars.compile([
            '<p class="repo-language">{{province}}</p>',
            '<p class="repo-name">{{name}}</p>',
            '<p class="repo-description">{{physical_address}}</p>'
        ].join(''))
    }
});

您将d.value传递到datumTokenizer中,因此它仅使用来自数组中每个元素的值对象。

还请注意Bloodhound对数据本身进行了标记,因此您不需要在JSON中传递单个标记(即不需要tokens对象)。

所以我将它更改为使用Bloodhound来标记数组中每个元素组合的valuephysical_address对象:

// constructs the suggestion engine
var films = new Bloodhound({
    datumTokenizer: function(d) { 
                      return Bloodhound.tokenizers.whitespace(d.name); 
                    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 15,
    prefetch: {
       url: _prefetch_url,
       filter: function(list) {
          return $.map(list, 
                 function(element) { 
                         return { name: element.value + " " + element.physical_address }; 
                 });
       }
    }
});

我只能在本地上下文中测试这个,但是预取应该以相同的方式工作。

相关内容

  • 没有找到相关文章

最新更新