始终显示自动填充列表,即使搜索不匹配也是如此

时间:2018-05-30 12:38:57

标签: javascript jquery ajax jquery-ui jquery-ui-autocomplete

我有一个自动填充字段,在类型I上转到PHP /数据库以检索匹配的选项。

事实是,我的建议清单与文本完全匹配。我解释一下:

说我输入" 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;
                    }
                });
            });
    	}     

    }




感谢。

1 个答案:

答案 0 :(得分:1)

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

您的代码可以像我想的那样简单,不需要在自动完成范围之外有单独的处理程序或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