在jquery自动完成中使用查找和/或服务URL

BKS*_*ngh 7 javascript jquery autocomplete jquery-autocomplete jquery-ui-autocomplete

我的应用程序中有一个自动完成功能,它向服务器发出ajax请求.但是,一旦我从服务器获取数据,我想使用查找功能而不是使用服务URL(以最小化对服务器的调用).

这是我的js的样子

$('#country').autocomplete({
    serviceUrl : './countryCache?',
    paramName : 'countryName',
    transformResult : function(response) {
        return {
            // must convert json to javascript object before process
            suggestions : $.map($.parseJSON(response), function(item) {
                return {
                    data : item.name
                };
            })
        };
    },
    showNoSuggestionNotice:true,
    onSelect: function (value, data) {
        $('#countryId').val(value.data);

    }

});
Run Code Online (Sandbox Code Playgroud)

以下是我的ajax调用countryCache的示例 - "印度,冰岛,印度尼西亚".如果用户键入了I,则服务器将返回上面的结果.现在,当用户在I之后键入n时,我不想再次调用服务器.有人可以帮助我实现它.

Alv*_*oro 5

jQuery UI Autocomplete文档中有一个简单的解决方案.在那里,您将找到一个名为Remote with caching的部分,其中显示了如何实现您正在寻找的内容.

我将该网站的代码改编为这个问题,并添加了一些注释以便澄清:

var cache = {};
$( "#country" ).autocomplete({
    source: function( request, response ) {
        // If the term is in the cache, use the already existing values (no server call)
        var term = request.term;
        if ( term in cache ) {
            response( cache[ term ] );
            return;
        }

        // Add countryName with the same value as the term (particular to this question)
        // If the service reads the parameter "term" instead, this line can be deleted.
        request.countryName = request.term;

        // Call the server only if the value was not in the cache
        $.getJSON( "./countryCache", request, function( data, status, xhr ) {
            cache[ term ] = data;
            response( data );
        });
    },
    select: function (event, data) {
        $('#countryId').val(data.item.value);
    }
});
Run Code Online (Sandbox Code Playgroud)

由于我不知道JSON的格式,我只是使用了一个基本的文本"In"返回:( ["India","Indonesia","Spain"]没有id,只是一个普通的数组).


如果您使用的是jQueryAjax AutoComplete插件(上面的代码看起来像它,虽然问题用标记),那么您不必担心缓存,因为插件会自动执行为了你.

从插件的文档:

noCache:布尔值,指示是否缓存建议结果.默认false.

由于您没有为其指定任何值nocache,因此它将采用默认值false,并且它将直接执行缓存.