Typeahead 0.10如何防止缓存

6

我使用Twitter的typeahead 0.10版本,并通过远程URL从服务器检索JSON结果。

我想要防止客户端缓存,以便搜索始终在服务器上进行。我该如何做?

请参见下面的代码:

 // instantiate the bloodhound suggestion engine
    var dataSource = new Bloodhound({
        datumTokenizer: function (d) {
            return Bloodhound.tokenizers.whitespace(d.value);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: "../" + autocompleteInfo.ControllerName + "/" + autocompleteInfo.MethodName + "?term=%QUERY&ts=" + (new Date().getTime()),
            filter: function (res) {
                var data = [];
                data = $.map(res, function (item) {
                    return { label: item.Name, id: item.Id, autocompleteInfo: autocompleteInfo, cssClass: item.Class };
                });

                return data;
            }
        },
        limit: 15,
        name: 'typeaheadSourceCache',
        ttl: 0,
        ajax: {
            cache: false
        }
    });

    dataSource.initialize();

    $("#" + autocompleteInfo.AutocompleteId).typeahead({
        minLength: 3,
        highlight: true,
        autoselect: true
    },
        { 
            displayKey: 'label',
            source: dataSource.ttAdapter(),
            templates: {
                suggestion: Handlebars.compile(
                '<div class="searchItem {{cssClass}}">{{label}}</div>'
                )
            }
        });

值得一提的是,在 Twitter Typeahead 社区中,有其他人也面临同样的问题,并且正在研究解决方案。例如,请参见:https://github.com/twitter/typeahead.js/pull/703 - Phil
请参见 https://github.com/twitter/typeahead.js/issues/564 - Vicentiu Berneanu
4个回答

29

只需将cache字段添加到remote对象中:

remote: { 'cache': false ... }


这正是我需要的。我有多个 Bloodhound 引擎,绑定到多个文本输入,每个都提供不同角色的用户列表(这是一大堆)。在从三个文本输入之一选择用户后,其他输入将显示第一个输入提供的用户列表。对于我的目的来说,这实际上是逻辑上不正确的。无论如何,感谢 Richard。 - Dan
3
应该选择这个作为答案。谢谢 Richard。 - David Routen
这绝对应该是被选中的答案。为什么在 https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md#remote 的文档下面没有提到这个选项呢? - Art Geigel
这绝对有效!只需记住,要刷新结果(如果您向数据源添加了更多结果),您必须更改当前自动完成搜索的至少一个字母。非常感谢! - joalcego

6

0
为了解决IE的问题,我找到了以下方法:
remote: {
url: '/myurl?par=%QUERY',
wildcard: '%QUERY',
prepare: function (q, o) {
        o.url = o.url.replace('%QUERY', encodeURIComponent(q));
        o.cache = false;
        return o;
    }
}

prefetch: {
    url: '/myurl2',
    ttl: 300000, //5min
    thumbprint: userName,
    prepare: function(o) {
        o.cache = false;
        return o;
}

0
尝试使用typeahead destroy utils,我认为在你的情况下是这样的:
$("#" + autocompleteInfo.AutocompleteId).typeahead('destroy');

你重新初始化$("#" + autocompleteInfo.AutocompleteId)


谢谢。我不想销毁并重新创建typeahead控件(或至少是typeahead使用的输入元素),其中一个原因是我没有适当的事件来执行此销毁/创建操作。我希望对于每个搜索的关键字,即使它以前已经被搜索过,也向服务器发出请求。 - Vicentiu Berneanu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接