当查询不在displayField中时,引导Ajax Typeahead不显示结果

Bootstrap-Ajax-Typeahead not showing results when query not in displayField

本文关键字:Ajax Typeahead 显示 引导 结果 中时 查询 displayField      更新时间:2023-09-26

我在Django应用程序上有一个Bootstrap Ajax Typeahead实现,该应用程序在我们的系统中搜索页面。我通过AJAX获得了与基于查询的搜索结果相匹配的页面,用户可以点击打字建议并转到有问题的页面。

但是,如果查询字符串不是displayField(title)的一部分,则建议不会显示,尽管我可以通过搜索机制看到它返回。

例如,如果我搜索"动态图片",我会通过搜索返回一个JSON对象,例如:

{
     title: "Movies",
     url: "/movies/",
     description: "Find a motion picture in your area"
}

当在description属性中找到匹配时,我仍然希望向用户显示结果,但Typeahead只会在有匹配提示时显示。

如何显示查询不在displayField中的搜索结果?

注意:我使用的是typeahead bootstrap w/Bv3。

$(document).ready(function ($) {
    var JSONSearchURL = "/search/";
    var searchBox = $('#search-form');
    searchBox.typeahead({
        onSelect: function (item) {
            window.location = item.value;
        },
        ajax: {
            url: JSONSearchURL,
            timeout: 800,
            displayField: "title",
            valueField: "url",
            method: "get",
            dataType: "JSON",
            preDispatch: function (query) {
                return {
                    q: query
                }
            },
            preProcess: function (data) {
                return data;
            }
        }
    });
});

默认情况下,bootstrap-ajax-typeahead使用displayField来搜索匹配项。如果要覆盖此行为并搜索另一个字段,则需要覆盖grepper事件。像这样的东西应该有效(未经测试):

grepper: function(data){
    var that = this;
    if(data && data.length){
        items = $.grep(data, function(item){
            return that.matcher(item['description']);
        });
        return items;
    }
    return null;
}

请在此处查看grepper的默认实现:https://github.com/biggora/bootstrap-ajax-typeahead/blob/master/src/bootstrap-typeahead.js#L283