我正在使用 Jquery 自动完成功能。如果用户键入 2 个字符然后等待,然后再键入另一个字符。如果第一个响应出现在第二个响应之后,它将短暂显示第二个列表,然后显示第一个列表。用户开始输入更多内容后,如何取消第一个请求?
$("#city").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/geo/json_autocomplete.php",
dataType: "json",
data: {
term: $("#city").val(),
countryid: $("#countryid").val()
},
success: function( data ) {
response( $.map( data, function( item ) {
//console.debug(item.value+" "+item.label+" "+item.id);
return {
label: item.label,
value: item.value,
id: item.id
}
}));
}
});
},
minLength: 2,
delay: 500,
select: function( event, ui ) {
$("#cityid").val(ui.item.id);
showForm();
}
});
最佳答案
您可以尝试将 xhr 存储在变量中,并将其与 AJAX 成功回调中获得的 xhr
参数进行比较。仅当两者匹配时才调用响应函数。您还可以相应地调整“延迟”参数。
var lastXhr;
$("#city").autocomplete({
delay: 500, // 500ms between requests.
source: function( request, response ) {
lastXhr = $.ajax({
url: "/geo/json_autocomplete.php",
dataType: "json",
data: {
term: $("#city").val(),
countryid: $("#countryid").val()
},
success: function( data, status, xhr ) {
if (xhr === lastXhr) {
response( $.map( data, function( item ) {
//console.debug(item.value+" "+item.label+" "+item.id);
return {
label: item.label,
value: item.value,
id: item.id
};
}));
}
}
});
},
minLength: 2,
delay: 500,
select: function( event, ui ) {
$("#cityid").val(ui.item.id);
showForm();
}
});
关于Jquery UI 自动完成显示较早文本的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9040929/