Bootstrap中的Typeahead:当输入不匹配时,建议会保留

时间:2013-04-16 08:44:16

标签: javascript twitter-bootstrap typeahead.js

我在Bootstrap中使用typeahead为我的应用程序使用Ajax从服务器端获取建议   一切都很好,除了:我正在写正确的输入并得到像“行尸走肉”这样的建议。当我开始输入错误的输入时,比如walkkkk,除非我按下ESC键,否则建议仍然存在。它让我烦恼。
enter image description here
  我检查了服务器端,当我开始输入错误的输入时,服务器什么都不返回   如何自动隐藏建议?

这是相对的js代码:

$('#query').typeahead({
    source: function(query, process){
        suggestions = {};
        labels = [];
        $.post('suggest.do', {query: query, limit: '10'}, function(data){
            var sugg = jQuery.parseJSON(data).data;

            if(sugg == 'NOTHING' || sugg == 'ERROR'){
                return;
            }
            $.each(sugg, function(index, item){
                suggestions[item.name] = item;
                labels.push(item.name);
            });
            return process(labels);
        });
    },
    items: 10,
    minLength: 1,
    updater: function(item){
        //irrelative code
    },
    matcher: function(item){
        return true;
    },
    highlighter: function(item){
        var ent = suggestions[item];
        var html = '' +
                    '<div class="entity-block">' +
                    '<span class="label label-important">' + ent.type + '</span>&nbsp;' + 
                    '<span class="sugg-name">' + ent.name + '</span>' +
                    '</div>';
        return html;
    }
});

1 个答案:

答案 0 :(得分:0)

source: function(query, process){
    suggestions = {};
    labels = [];
    $.post('suggest.do', {query: query, limit: '10'}, function(data){

        //Check if any data is returned, if not clear the text and exit the func
        if(!data || data.length == 0){
           $('#query').val("");
           return;
        }

        var sugg = jQuery.parseJSON(data).data;

        if(sugg == 'NOTHING' || sugg == 'ERROR'){
            return;
        }
        $.each(sugg, function(index, item){
            suggestions[item.name] = item;
            labels.push(item.name);
        });
        return process(labels);
    });
},