问题
I'm using Jquery autocomplete. If a user types 2 characters then waits, then types another. If the first response comes after the second, it will briefly show the second list then show the first list. How can I cancel the first request after a user starts typing more?
$("#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();
}
});
回答1:
You could try storing the xhr in a variable and comparing it with the xhr
parameter you get in the AJAX success callback. Only call the response function if the two match. You can also adjust the "delay" parameter accordingly.
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();
}
});
来源:https://stackoverflow.com/questions/9040929/jquery-ui-autocomplete-shows-response-for-earlier-text