Jquery UI自动完成显示早期文本的响应

我正在使用Jquery自动完成function。 如果用户键入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(); } });