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



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

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

假设我输入"乔恩"。我的列表将从数据库中带来"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(,以便它是执行所有过滤的后端。现在,自动完成功能实际上认为您已经向它提供了应从中进行进一步筛选的选项的静态列表,因此它决定处理筛选本身。

我认为您的代码可以像这样简单,无需在自动完成范围之外使用单独的处理程序或 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。

最新更新