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

use lookup and/or service url in jquery autocomplete

本文关键字:查找 url 服务 jquery      更新时间:2023-09-26

我的应用程序中有一个自动完成功能,可以向服务器发出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调用中的一个示例——"印度、冰岛、印度尼西亚"。如果用户输入了I,服务器会返回上面的结果。现在,当用户在我之后键入n时,我不想再打电话给服务器。有人能帮我实现吗?

jQuery UI Autocomplete文档中有一个简单的解决方案。在那里,您可以找到一个标题为带缓存的远程的部分,它显示了如何实现您想要的功能。

我根据这个问题调整了该网站的代码,并添加了一些注释进行澄清:

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,只有一个普通数组)。


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

来自插件文档:

noCache:表示是否缓存建议结果的布尔值。默认false

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

我最终根本没有使用这个方法,而是以100为限制进行快速搜索。但既然我问了,下面是我如何只使用第一个字符发送请求的:

 // global variables: models [], result {}
          lookup: function(query, done) {
                var mdl = $("#autocomplete").val();
                if (mdl.length == 0) {
                    names = [];
                    result.suggestions = models;
                    done(result);
                    return;
                } else if (mdl.length != 1) {
                    result.suggestions = names;
                    console.log(result);
                    done(result);
                    return;
                }
                var jqHXR = $.ajax({url: "search.php",   
                        data: {"q": mdl},
                        dataType: "json",
                        method: "GET" }
                )
                .done(function(data, status, jqXHR){
                    models = [];
                    $.each( data, function( key, val) {
                        names.push({ value: val.u, data: { category: genders[val.g] } });
                    });
                    result.suggestions = names;
                    done(result);
                })
                .fail(function (data, status, errorThrown) {
                        console.log("failed: "+status+"| error: "+errorThrown);
                        console.log(data);
                });
            },

我的一位同事使用了devbridge,我的研究似乎验证了minChars和lookupLimit的devbridgeAutocomplete对象有一个属性。也许有不同的devbridgeAutocomplete实例,但我认为值得发布,以防它们相似,尽管我认为你已经看到了:)。

这是代码:

var a =  $('#<%= txtFindName.ClientID %>').devbridgeAutocomplete({
           minChars: 3,
           lookupLimit: 20,
            serviceUrl: 'AutoComplete/ADUsers.aspx',
            onSelect: function (suggestion) {
                $('#<%= txtTo.ClientID %>').val( $('#<%= txtTo.ClientID %>').val() + ',' + suggestion.data);
                $('#<%= txtFindName.ClientID %>').val('');
            }
       });