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

标签 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);

    }

});

这是我对 countryCache 的 ajax 调用的示例 - “India, Iceland, Indonesia”。 如果用户输入了 I,服务器返回如上的结果。 现在,当用户在我之后输入 n 时,我不想再次调用服务器。 谁能帮我实现它。

最佳答案

jQuery UI Autocomplete documentation 中有一个简单的解决方案.您会在此处找到标题为带缓存的远程 的部分,其中显示了如何实现您正在寻找的内容。

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

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);
    }
});

因为我不知道 JSON 的确切格式,所以我只使用了一个基本的格式,用于返回文本“In”:["India","Indonesia","Spain"](没有 ID,只是一个普通数组)。


如果您使用的是 Ajax AutoComplete plugin for jQuery (上面的代码看起来像,虽然问题被标记为 ),那么您不必担心缓存,因为插件会自动为您完成

来自插件的文档:

noCache: Boolean value indicating whether to cache suggestion results. Default false.

因为你没有给nocache指定任何值,那么它会取默认值false,直接执行缓存。

关于javascript - 在 jquery 自动完成中使用查找和/或服务 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26561289/

相关文章:

javascript - Netsuite Suitescript API - 搜索交易记录返回重复项

php - 努力用一个小的json和php来获取IP

javascript - 无法读取 null 的属性 'length' - 使用 css 显示 block (选择/onchange)

css - 在 Visual Studio Code 中防止自动分号

javascript - angucomplete-alt 从远程 url 获取数据的问题

html - 在 jQuery UI 自动完成中使用 HTML

Javascript函数变量预设

javascript - i18n nodejs 和前端 javascript 本地化

javascript - 如何在Javascript中的div中的按钮中知道按下的按钮

javascript - 使用异步等待获取失败时如何捕获状态代码