ajax – 导航时替换Bootstrap typeahead建议

我正在使用Bootstrap Typeahead建议som搜索结果.结果是从ajax ressource返回的,由于这个资源造成延迟,我遇到了一个不幸的影响.

例:
如果输入一个4个字母的单词,建议将显示在2个字母之后,然后我可以使用键向上/向下查看结果,但突然建议将重新加载,因为上一个请求已完成.

有没有办法“取消”任何剩余,如果用户当前正在使用键上/下来完成建议?

('#query').typeahead({
        items: 4,
        source: function (query,process) {

            map = {};
            $.getJSON('/app_dev.php/ajax/autosuggest/'+query, function (data) {
                vehicles = [];
                $.each(data, function(i,vehicle){
                    map[vehicle.full] = vehicle;
                    vehicles.push(vehicle.full);
                });
                process(vehicles);
            });
        },
        updater: function (item) {
            // do something here when item is selected
        },
        highlighter: function (item) {
            return item;
        },
        matcher: function (item) {
            return true;
        }
    });

最佳答案 我认为以下内容将满足您的需求(难以完全重现):

没有简单的方法来中止延迟响应,但你可以扩展typeahead as I figured out here(不修改bootstrap.js)

概念是捕获keydown,检测事件是否为KEY_UP或KEY_DOWN,设置标志is_browsing,然后如果is_browsing为真则中止进程(即,如果用户已经命中KEY_UP或KEY_DOWN,之后没有其他键).

扩展预先输出:

// save the original function object
var _superTypeahead = $.fn.typeahead;

// add is_browsing as a new flag
$.extend( _superTypeahead.defaults, {
    is_browsing: false
});

// create a new constructor
var Typeahead = function(element, options) {
    _superTypeahead.Constructor.apply( this, arguments )
}

// extend prototype and add a _super function
Typeahead.prototype = $.extend({}, _superTypeahead.Constructor.prototype, {
    constructor: Typeahead

    , _super: function() {
        var args = $.makeArray(arguments)
        // call bootstrap core
        _superTypeahead.Constructor.prototype[args.shift()].apply(this, args)
    }

    //override typeahead original keydown
  , keydown: function (e) {
      this._super('keydown', e)
      this.options.is_browsing = ($.inArray(e.keyCode, [40,38])>-1)
    }

    //override process, abort if user is browsing
  , process: function (items) {
      if (this.options.is_browsing) return
      this._super('process', items)
    }

});

// override the old initialization with the new constructor
$.fn.typeahead = $.extend(function(option) {
    var args = $.makeArray(arguments),
    option = args.shift()

    // this is executed everytime element.modal() is called
    return this.each(function() {
        var $this = $(this)
        var data = $this.data('typeahead'),
            options = $.extend({}, _superTypeahead.defaults, $this.data(), typeof option == 'object' && option)

        if (!data) {
            $this.data('typeahead', (data = new Typeahead(this, options)))
        }
        if (typeof option == 'string') {
            data[option].apply( data, args )
        }
    });
}, $.fn.typeahead);

这种类型扩展可以放置在任何地方,例如在< script type =“text / javascript”>中. -部分

测试扩展:

<input type="text" id="test" name="test" placeholder="type some text" data-provide="typeahead">
<script type="text/javascript">
$(document).ready(function() {
    var url='typeahead.php';
    $("#test").typeahead({
        items : 10,
        source: function (query, process) {
            return $.get(url, {  query: query }, function (data) {
                return process(data.options);
            });
        }
    });
});
</script>

一个“服务器端”PHP脚本,返回大量带有强制延迟的随机选项,typeahead.php:

<?
header('Content-type: application/json');
$JSON='';
sleep(3); //delay execution in 3 secs
for ($count=0;$count<30000;$count++) {
    if ($JSON!='') $JSON.=',';
    //create random strings
    $s=str_shuffle("abcdefghijklmnopq");
    $JSON.='"'.$s.'"';
}
$JSON='{ "options": ['.$JSON.'] }';
echo $JSON;
?>

它似乎真的对我有用.但我无法确定它是否适用于您的情况.如果你有成功,现在让我.

点赞