奇怪的行为Typeahead与远程JSON

时间:2015-05-07 10:48:07

标签: javascript jquery ajax typeahead.js typeahead

我有一种非常奇怪的行为,我试图了解最近几个小时。

我已经自我解释了JSFiddle you can find here.

Stackoverflow在没有代码的情况下不接受jsfiddle,所以我们在这里......:

$(function(){
    var $el = $('#typeahead');
    var resultsObj = {};
    var resultsStrings = [];
    var engine = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.whitespace, 
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: '/echo/json/',  
            prepare: function(xhr, settings) {
                settings.dataType = 'json';
                settings.type = 'POST';
                settings.data = {json: fakeSearchForFiddle($el.typeahead('val'))};
                return settings;
            }, 
            transform: function(data) {
                showRawResult(data);

                resultsObj = {};
                resultsStrings = [];

                if ($.isArray(data)) {
                    for (var i = 0; i < data.length; ++i) {
                        resultsObj[data[i].ref] = data[i];
                        resultsStrings.push(data[i].ref);
                    }
                }
                return resultsStrings;
            }
        }
    });
    engine.initialize();

    $el.typeahead({
        highlight: false
    }, {
        name: 'main', 
        source: engine.ttAdapter(), 
        templates: {
        empty: '<div class="empty-message">No result</div>', 
            suggestion: function(data) {
                if (resultsObj[data] !== undefined) {
                    return '<div>'+resultsObj[data].ref+' <span>('+resultsObj[data].details+')</span></div>';
                }
                return '<div>Unknown</div>';
            }
        }
    });
});

服务器返回一个JSON数组,该数组由包含&#34; ref&#34;和&#34;详细信息&#34;键。 此测试的目标是使用以下语法显示建议:

&#34; result.ref&lt; span&gt;(result.details)&lt; / span&gt;&#34;

它适用于1个结果,或者两个,或者超过5个结果。否则它完全搞砸了,我不明白为什么。

我花了几个小时尝试不同的事情,但无法使其发挥作用,文档也非常模糊。

感谢您的帮助。

编辑I've posted an issue on Github

1 个答案:

答案 0 :(得分:1)

我对typeahead.js的源代码进行了一些小修改,因为我需要尽快使用这个东西。

问题来自&#34; typeahead.bundle.js:1719 &#34; :

function async(suggestions) {
    suggestions = suggestions || [];
    if (!canceled && rendered < that.limit) {
        that.cancel = $.noop;
        rendered += suggestions.length;
        that._append(query, suggestions.slice(0, that.limit - rendered));
        that.async && that.trigger("asyncReceived", query);
    }
}

我已经取代了:

rendered += suggestions.length;
that._append(query, suggestions.slice(0, that.limit - rendered));

by:

suggestions = (suggestions || []).slice(0, that.limit);
rendered = suggestions.length;
that._append(query, suggestions);

它似乎工作..我不知道这个修改可能产生的副作用,所以我会在typeahead的github上发布它,希望他们更新库或者解释我的内容做错了。

编辑Github issue