始终显示自动完成列表,即使搜索不匹配

Always show autocomplete list, even if search doesn't match

我有一个自动完成字段,在输入时我转到 PHP/Database 以检索匹配的选项。

问题是,我的建议列表与文本不完全匹配。我解释:

假设我输入 "Jon"。我的列表将从数据库 "John Doe"、"Jonatan" 等中获取。只有 "Jonatan" 会作为对输入的建议可见,但我确实需要它们,因为它考虑了近似值(有我的后端搜索中的 soundex 元素)。

我的JavaScript/Ajax代码:

function prePatientsList(){
      //I'm limiting search so it only starts on the second character
     if (document.getElementById("name").value.length >= 2) { 

            try
            {
             listExecute.abort();
         }catch(err) {
            null;
         }
            var nome= $("#name").val();
            var nomeList = "";
            listExecute = $.ajax({
                    url: '/web/aconselhamento/Atendimento/PrePacientesAutocomplete',
                    type: "POST",
                    async: true,
                    datatype: 'json',
                    data: { nome: nome}
             }).done(function(data){
              source = JSON.parse(data);
             });
            
            
            $(function() {
             $("input#nome").autocomplete({
                    source: source,
                    // I know I probably don't need this, but I have a similar component which has an URL as value, so when I select an option, it redirects me, and I'll apply you kind answer on both.
                    select: function( event, ui ) {                     
                        ui.item.label;
                    }
                });
            });
     }     

    }

谢谢。

我认为您必须将您的远程端点直接设置为自动完成的源(例如类似于 https://jqueryui.com/autocomplete/#remote),以便它是执行所有过滤的后端。现在,自动完成实际上认为您已经为它提供了一个 static 选项列表,应该从中进行进一步的过滤,因此它决定自己处理过滤。

您的代码可以像我想的那样简单,不需要单独的处理程序或自动完成范围之外的 ajax 请求。

$(function() {
  $("input#nome").autocomplete({
    minLength: 2, //limit to only firing when 2 characters or more are typed
    source: function(request, response) 
    {
      $.ajax({
        url: '/web/aconselhamento/Atendimento/PrePacientesAutocomplete',
        type: "POST",
        dataType: 'json',
        data: { nome: request.term } //request.term represents the value typed by the user, as detected by the autocomplete plugin
     }).done(function(data){
         response(data); //return the data to the autocomplete as the final list of suggestions
     });
    },
    // I know I probably don't need this, but I have a similar component which has an URL as value, so when I select an option, it redirects me, and I'll apply you kind answer on both.
    select: function( event, ui ) {                     
      ui.item.label;
    }
  });
});

有关详细信息,请参阅 http://api.jqueryui.com/autocomplete/#option-source