提前输入:有时没有错误提示,但会加载ajax结果

时间:2018-10-11 12:10:27

标签: javascript jquery typeahead.js

我创建了一个带有自动寻血犬的自动提示建议。

猎犬代码:

var addresses = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: Routing.generate('manage_ajax_addresses_search') + '?q=%QUERY',
        wildcard: '%QUERY',
        cache: false
    },
    prefetch: {
        url: Routing.generate('manage_ajax_addresses_search')
    }
});

预先输入初始化代码:

$('#input').typeahead(null, {
    name: 'addresses',
    source: addresses,
    display: 'search',
    minLength: 0,
    items: 99999,
    autoSelect: true,
    showHintOnFocus: true,
    templates: {
        suggestion: function (data) {
            return '<div>' + data.company + '<small>' + data.address + ', ' + data.zip + ' ' + data.city + '</small></div>';
        },
        pending: function (data) {
            return '<div style="padding: 4px;"><img src="https://cdn.wwnbg.de/img/ajax-loader/ajax-loading-truck.gif" height="30px;" <i>Suche läuft...</i></div>';
        },
        notFound: function (data) {
            return '<div style="padding: 4px;"><small><i>Keine passenden Einträge gefunden.</i></small></div>';
        },
        header: function (data) {
            return '';
        }
    }
});

但是,当我在输入中键入“ Made”时,将加载包含此字符串的条目。如果输入“ Mader”,则将执行Ajax请求,该请求将返回正确的结果,但是自动建议将显示“未找到条目”。我该如何解决?

1 个答案:

答案 0 :(得分:-1)

您可以编写如下代码:

$('#input').typeahead(null, {
    name: 'addresses',
valueKey: 'address'
    source: addresses,
    display: 'search',
    minLength: 0,
    items: 99999,
    autoSelect: true,
    showHintOnFocus: true,
    templates: {
        suggestion: function (data) {
            return '<div>' + data.company + '<small>' + data.address + ', ' + data.zip + ' ' + data.city + '</small></div>';
        },
        pending: function (data) {
            return '<div style="padding: 4px;"><img src="https://cdn.wwnbg.de/img/ajax-loader/ajax-loading-truck.gif" height="30px;" <i>Suche läuft...</i></div>';
        },
        notFound: function (data) {
            return '<div style="padding: 4px;"><small><i>Keine passenden Einträge gefunden.</i></small></div>';
        },
        header: function (data) {
            return '';
        }
    }
});